Brian Zengel
Brian Zengel

Reputation: 546

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:

Upvotes: 13

Views: 42111

Answers (2)

Zoltan Toth
Zoltan Toth

Reputation: 47667

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>

Upvotes: 25

user1133972
user1133972

Reputation: 21

You could use the negative margin method to vertically center the text. To do that you could put your text in a <span> and have the following css:

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;
}

table.float td img
{
    float: left;
}

table.float td span
{
    position: absolute;
    top: 50%;
    margin-top: -10px; /* or half of the height of your text */
}

Upvotes: 1

Related Questions