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

标签 html css flexbox

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

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

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

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

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

或者这个:

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

与第二个选项相比,我更喜欢第一个选项,因为对于第二个选项,您可能会问,“为什么在其他独立于表格的内容中间有一个表格单元格?”

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

哪个选项在语义和浏览器支持方面更好?

最佳答案

要垂直居中内容,无需嵌套额外的包装器,您可以简单地使用 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 成为 flex 容器时,文本会被包裹在 anonymous container 中。成为 flex 元素。这就是 CSS 的工作原理。如果您不将内容包装在 HTML 元素中,CSS 将创建 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.

从功能的 Angular 来看,两者之间没有区别:

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

<td>my content</td>

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

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

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

您对 div 执行相同的操作, 通过覆盖浏览器的 display: block用你自己的display: table-cell .

所以就功能和所有播放器而言,这真的是一回事 – div , td , display: table-cellvertical-align: middlesupported by all browsers至少回到 IE6。

然而,浏览器对 flexbox 的支持尚未完成。所有主流浏览器都支持 CSS3 的 Flexbox,except IE 8 & 9 .一些最新的浏览器版本,例如 Safari 8 和 IE10,需要 vendor prefixes .要快速添加所需的所有前缀,请在此处发布您的 CSS: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>.

关于html - 如何在不嵌套额外容器的情况下垂直对齐内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34302060/

相关文章:

javascript - JQuery 工具提示效果不起作用

asp.net - 如何让 mailto 适用于 IDN 电子邮件 ID

jquery - 如何在 jquery 对话框中将按钮更改为图片

html - 用 div 做一个圆圈的替代方法

javascript - 我是否需要等待 DOM 就绪才能将类添加到 <body>?

html - Css 规则不起作用

firefox - Chrome/Firefox 上的盒子模型尺寸

javascript - 为什么我的 react-native 组件会重叠

html - 为什么 vuetify 数据表会拉伸(stretch)整个页面而不是渲染滚动条?

html - 为什么 flex-wrap : wrap not work on safari