Brian Zengel Brian Zengel - 17 days ago 5
CSS Question

centering text vertically and horizontally in same table cell with image floated left

I know this probably seems like a little problem. It just feels like there should be an easy solution. I have a feeling I'm SOL but I figured I'd ask first.

http://jsfiddle.net/bczengel/FSDz9/5/

Problem:



When the image is not floated left it has the desired end result where the image and the text are both vertically centered. When you float the image left the image is vertically centered and the text is aligned with the top of the image.

Requirements:




  • One table cell

  • CSS only with the given html (or minimal changes to the html)

  • I would like to avoid a line-height solution because the stylesheet is applied to many existing pages some of which have multiple lines in the text


Answer

with a minimal html change (wrapping your title text in a <p>)

table {
    width: 500px;
    border: solid 1px black;
}

table td {
    text-align: center;
    vertical-align: middle;
    padding: 5px;
    position: relative;
}

table td img {
    width: 50px;
    vertical-align: middle;
    display: inline-block;
}

table td p {
    display: inline-block;
    width: 430px;
    background: #ccc;
    vertical-align: middle
}
<table>
  <tr>
    <td>
      <img alt="test" src="http://t1.gstatic.com/images?q=tbn:ANd9GcQ-nkjB-srUT_dc7brfRDiDSVu8BQa_6TEbQYevP1gy2UkTdcXWzg" />
      <p>Title Text</p>
    </td>
  </tr>
</table>

<br /><br />

<table>
  <tr>
    <td>
      <img alt="test" src="http://t1.gstatic.com/images?q=tbn:ANd9GcQ-nkjB-srUT_dc7brfRDiDSVu8BQa_6TEbQYevP1gy2UkTdcXWzg" />
      <p>Title Text <br /> on the next line</p>
    </td>
  </tr>
</table>

Comments