Drupal website specialists.

Align images within a div easily using CSS

Posted 16/March/2010 by neubreed

After reading this you'll be able to center-align an image within a div using CSS (without the cross-browser headaches that margins and padding can cause).

First and foremost, check that you're using the correct doctype. We found that using the following doctype worked a treat across all browsers in this case.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    1. Set a height and width on the containing div, then apply a line-height that is equivalent to the div's height e.g.
      .img container  {
        width: 193px;
        height: 95px;
        line-height: 95px;
      }

      (if you like, add a green border because it's a pretty epic colour and borders rock.)

    2. You'll notice that the image is being treated the same as text would be, so go ahead and add text-align: center; e.g.
      .img container  {
        width: 193px;
        height: 95px;
        line-height: 95px;
        text-align: center;
      }
    3. Things should now be taking shape, and the only thing left to do is adjust the vertical alignment of the image, which is done easily using the following.
      .img container img  {
        vertical-align: middle;
      }

Your image should now be sitting neatly in the center of the containing div - no padding necessary, and therefore less browser headaches.