vertically and horizontally centering an image in a table cell using CSS

Discussion in 'Web Design and Development' started by torndownunit, Mar 8, 2009.

  1. macrumors regular

    Joined:
    Jan 4, 2009
    #1
    Hey guys. This is one of those things that I never really thought much about till I started to use mainly CSS.

    I have a table (containing tabular data of course) that has small images next to product descriptions. I am trying to center the images both vertically and horizontally in the cell. I can find info on how each should be set online, but I can't seem to combine them properly.

    It's one of those situation where I read several methods online, but the advice people give me on here will likely be (a) more current, and (b) way easier to understand and apply.

    Thanks
     
  2. Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #2
    I ran a simple case:
    HTML:
    <style type="text/css">
    td {
     width: 750px; height: 600px;
     text-align: center;
     border: 1px solid #000;
    }
    </style>
    </head>
    <body>
    <table>
    <tr>
      <td><img src="image01.jpg" alt="image 1" width="640" height="480" /></td>
    </tr>
    </table>
    and the image was centered vertically and horizontally. The td seems to default to a vertical alignment of middle in most browsers. Also, img are display: inline by default. If the img is block instead then you'll need to add,
    Code:
    td img {
     display: block;
     margin: 0 auto;
    }
    to get the img to center horizontally. At least that's what I was seeing in my limited testing. The techniques for centering in tables haven't changed in a good while so whatever you've come across is likely still the common methods.
     

Share This Page