To center content vertically without using additional wrappers, you can utilize flexbox.
CSS
div {
display: flex;
align-items: center; /* to vertically center content */
justify-content: center; /* optional - horizontally center content */
}
HTML
<div>my content</div>
DEMO
Keep in mind that even though it may seem like the text within the div has no containing element, technically, when the div is turned into a flex container, an anonymous container is created wrapping the text as a flex item. This is how CSS functions. If your content isn't wrapped in an HTML element, CSS generates anonymous block or inline boxes.
Your response:
I prefer the first option over the second because the second one makes me wonder why there is a Table Cell amidst other independent content.
I'm hesitant about using either options due to uncertainty of cross-browser compatibility for both.
Functionally, there isn't much difference between:
<div style="display:table-cell;">my content</div>
and
<td>my content</td>
Both achieve the same result. Here's why:
HTML elements like div
and td
do not have a defined display
value until the browser applies styles with the default stylesheet.
Hence, a td
behaves like a table cell because the default stylesheet specifies td { display: table-cell; }
.
By setting display: table-cell
on the div
, you are essentially doing the same thing as the browser does with td
.
Therefore, functionality-wise, they are equivalent, and all components - div
, td
, display: table-cell
, and vertical-align: middle
- are supported by virtually all browsers dating back to at least IE6.
On the other hand, complete support for flexbox, which is CSS3, across all browsers is still pending. Flexbox is compatible with major browsers, excluding IE 8 & 9. Some recent versions such as Safari 8 and IE10 require vendor prefixes. You can easily add the necessary prefixes using tools like Autoprefixer.
Additional Info:
HTML elements inherently lack any styling. The tag names themselves do not carry any styles. Styles are only applied once they pass through the browser, including properties like display
. (Refer to the HTML Default
Stylesheet.)
According to this MDN Bug
Report,
it seems that only some specific HTML elements such as <button>
, <fieldset>
, and <legend>
construct their boxes based on their tag names.