Search code examples
htmlcssimagevertical-alignment

Why does a table cell with a vertically-aligned element not align with a table cell without it?


The CSS property vertical-align is supposed to position text with relation to the element. But is it actually aligning?

https://codepen.io/wammygiveaway/pen/BagwRoq

HTML

<TABLE>
 <TR>
  <TD>Here is a cell with vertical alignment.<IMG src="sometext"></TD>
  <TD>Here is a cell without an alignment.</TD></TR></TABLE>

CSS

TABLE {
    width: 50%;
    margin: 0px auto;
    border-spacing: 0px;
    TD {
        border: 1px solid black;
        padding: 0px;
        width: 50%;
    }
    IMG {
        vertical-align: middle;
    }
}

In this CodePen example, I will be using an IMG tag as the element, and the container a table. On the left cell, you have some text and an IMG tag applied with vertical-align. On the right cell, you have just text. On the surface, both do seem aligned, even with the added measures of the border-spacing and padding modifiers. But if you zoom in very close, you will find that the cell with the vertically-aligned IMG makes the whole element veer off by a couple of pixels.

enter image description here

Which cell represents correct vertical alignment, one where you need an extra element like an IMG to implement a vertical-align property, or the other where it's preset for you so long as there are no other elements? Furthermore, how can I make it so that both table cell's texts are aligned equally regardless of the presence of an IMG tag in a cell that needs it?


Solution

  • Both cells have "correct" vertical alignment, obviously, even if it's not what you expect. This is controlled by the default setting of table-cell type vertical-alignment which for a <TD> element is middle and means that the text and image contents of the cell are vertically centered within the cell.

    This points the way to make the texts in each cell line up. Change the vertical alignment of the <TD> element to baseline.

    TABLE {
        width: 90%;
        margin: 0px auto;
        border-spacing: 0px;
        TD {
            border: 1px solid black;
            padding: 0px;
            width: 50%;
            vertical-align: baseline;
        }
        IMG {
            vertical-align: middle;
        }
    }
    <TABLE>
     <TR>
      <TD>Here is a cell with vertical alignment.<IMG src="sometext"></TD>
      <TD>Here is a cell without an alignment.</TD></TR></TABLE>