I was told that vertical-align only works for inline, and table elements, however, today I was playing around with vertical-align on a block element, it works just fine? How is that possible? In this case, does vertical-align work for all element types? Or if not, what doesn't it work on?
#wrap {
border: 1px solid black;
width: 500px;
height: 500px;
}
#alignTop {
vertical-align: top;
border: 1px solid black;
}
<div id = 'wrap'>
<div id = 'alignTop'> alignTop </div>
</div>
According to explanations documented on This link:
- HTML layout traditionally was not designed to specify vertical behavior. By its very nature, it scales width-wise, and the content flows to an appropriate height based on the available width. Traditionally, horizontal sizing and layout is easy; vertical sizing and layout was derived from that.
vertical-align
is used to specify two completely different behaviors depending on where it is used
When used in table cells, vertical-align
does what most people expect it to, which is mimic the (old, deprecated) valign
attribute. In a modern, standards-compliant browser, the following three code snippets do the same thing:
<td valign="middle"> <!-- but you shouldn't ever use valign --> </td>
<td style="vertical-align:middle"> ... </td>
<div style="display:table-cell; vertical-align:middle"> ... </div>
When vertical-align
is applied to inline elements, however, it's a whole new ballgame. In this situation, it behaves like the (old, deprecated) align
attribute did on <img>
elements. In a modern, standards-compliant browser, the following three code snippets do the same thing:
<img align="middle" ...>
<img style="vertical-align:middle" ...>
<span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>