如何在不嵌套额外容器的情况下垂直对齐内容?

How to vertically align content without nesting additional containers?

我在垂直对齐容器中的项目时遇到了很多麻烦。

我已经实施了很多建议。他们都建议将内容包装在另一个 div 或容器中。

由于各种原因,这导致了各种各样的问题,我不会讨论,但我想选择一个新要求:它不能被包装在另一个容器中。

这让我找到了这个解决方案(为简洁起见,内联样式):

<div style="display:table-cell;vertical-align:middle">my content</div>

或者这样:

<td style="vertical-align:middle">my content</td>

比起第二个,我更喜欢第一个选项,因为第二个选项,"why is there a Table Cell in the middle of this other content that is independent of a table?"

我对使用第一个选项犹豫不决的原因是因为我不确定它是否适用于所有浏览器。我也可以对第二种选择说同样的话。

就语义和浏览器支持而言,哪个选项更好?

要垂直居中内容,无需嵌套额外的包装,您可以简单地使用 flexbox

CSS

div {
    display: flex;
    align-items: center;       /* center content vertically, in this case */
    justify-content: center;   /* center content horizontally, in this case (optional) */
}

HTML

<div>my content</div>

DEMO

请注意,虽然 div 中的文本似乎没有容器,但从技术上讲,当 div 成为弹性容器时,文本会被包裹在 anonymous container that becomes the flex item. This is how CSS works. If you don't wrap your content in an HTML element, CSS will create anonymous block or inline boxes.


您写道:

I like the first option more than the second because the second you sort of go, "why is there a Table Cell in the middle of this other content that is independent of a table?

The reason I'm hesitant to use the first option is because I'm not sure it will work in all browsers. I could say the same about the second option as well.

从功能的角度来看,两者没有区别:

<div style="display:table-cell;">my content</div>

<td>my content</td>

两者做同样的事情。原因如下:

HTML 元素,包括 divtd,没有 display,直到浏览器应用带有 default stylesheet 的样式.

因此,td 像 table 单元格一样工作的唯一原因是浏览器的默认样式表指定 td { display: table-cell; }.

您对 div 执行相同的操作,方法是用您自己的 display: table-cell.

覆盖浏览器的 display: block

因此,就功能而言,所有播放器都是一样的 – divtddisplay: table-cellvertical-align: middle supported by all browsers 回归至少 IE6.

但是,浏览器对 flexbox 的支持尚未完成。 Flexbox,也就是CSS3,所有主流浏览器都支持,except IE 8 & 9. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add all the prefixes you need, post your CSS here: Autoprefixer.


As an aside:

HTML elements have no inherent styling. In other words, the tag names themselves don't carry styles. It isn't until they go through the browser that display and other CSS properties are applied. (See an HTML Default Stylesheet.)

Based on this MDN Bug Report, it appears that the only HTML elements who's boxes are constructed based on their tag name are <button>, <fieldset> and <legend>.

CSS 表格被大约 97% 的浏览器支持,并且向后兼容性好,参见 http://caniuse.com/#feat=css-table

我会毫不犹豫地使用 CSS 表格,你的例子是完全合理的。