Search code examples
htmlcsshtml-tablecentering

Centering images within 300 px by 300 px table grid


My code is below and I'm looking for the best way via CSS to center an image (horizontally and vertically) in a 300 by 300 pixel square. Larger images will be fit down to that size and smaller images should be centered, not stretched.

<table width="100%">
  <tr>
    <td><div class="300box"><img class="centeredimage" /></div></td>
    <td><div class="300box"><img class="centeredimage" /></div></td>
    <td><div class="300box"><img class="centeredimage" /></div></td>
  </tr>
</table>

css:

.300box {
  height: 300px;
  width: 300px;
}

.centeredimage {
  vertical-align: middle;
  text-align: center;
}

I know the above is incorrect so I'm hoping to find a more efficient way to do it. Each table row has 3 300x300 pixel divs with images centered within.


Solution

  • Using a div inside a td is not worse than any other way of using tables.

    You can try this--

    CSS:

    .blocks.table td {
        width: 300px;
        height: 300px;
        border: 1px solid #ff0000;
        vertical-align: middle;
        text-align: center;
    }
    p.centeredimage img {
        max-height: 300px;
        max-width: 300px;
    }
    

    HTML:

    <table width="100%" class="table blocks">
        <tr>
            <td>
                <p class="centeredimage" ><img src = "http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/185106_431273290248855_254736287_n.jpg" /></p>
            </td>
    
            <td>
                <p class="centeredimage" ><img src = "http://a6.sphotos.ak.fbcdn.net/hphotos-ak-ash4/304640_10151181184992355_456123210_n.jpg" /></p>
            </td>
            <td>
                <p class="centeredimage" ><img src = "http://sphotos-b.ak.fbcdn.net/hphotos-ak-snc7/s480x480/422953_410146439043183_1035950087_n.jpg" /></p>
            </td>
            <td>
                <p class="centeredimage" ><img src = "http://sphotos-e.ak.fbcdn.net/hphotos-ak-ash3/s480x480/561574_467101546644877_728463753_n.jpg" /></p>
            </td>
        </tr>
    </table>