为什么 margin: auto 只能水平工作而不能垂直工作?
我发现,在开发网站时,在随机高度的容器内垂直居中容器(固定高度)对于 Web 开发人员(至少是我)来说总是一场噩梦,而当涉及到水平居中容器(固定高度)时, width)在随机宽度的容器内,margin:0px auto; 往往在标准模型中提供一种简单的解决方法。
当事情可以如此简单时,为什么 CSS 在将固定高度的容器置于随机高度的容器内居中时不使用 margin:auto 0px;
来解决呢?这样做有什么具体原因吗?
I have seen that while developing websites, vertically centering a container (of fixed height) inside a container of random height always comes as a nightmare for the web developer (at least, me) while when it comes to horizontal centering a container (of fixed width) inside a container of random width, the margin:0px auto;
tends to serve an easy way out in the standard model.
When things can be as simple as that why doesn't CSS work out with the margin:auto 0px;
when it comes to centering a container of fixed height inside a container of random height? Is there any specific reason to do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这确实没有你想象的那么可怕,只是不要使用边距。
vertical-align
确实是您应该依赖的流体高度垂直居中。我整理了一个快速演示来证明我的观点:请参阅:http://jsfiddle.net/Wexcode/jLXMS/
It's really less of a nightmare than you think, just don't use margins.
vertical-align
is really what you should rely on for fluid-height vertical centering. I threw together a quick demo to demonstrate my point:See: http://jsfiddle.net/Wexcode/jLXMS/
您问题的正确答案是
margin: auto 0
的工作方式与margin: 0 auto
的工作方式不同,因为width: auto
与height: auto
的工作方式不同。垂直自动边距适用于具有已知高度的绝对定位元素。
The right answer for your question is that
margin: auto 0
doesn't work the same way thatmargin: 0 auto
works becausewidth: auto
doesn't work the same wayheight: auto
does.Vertical auto margin works for absolutely positioned elements with a known height.
使用 flexboxparent
与
justify-content: center
/align-items: center
相比,使用margin: auto
的优点之一是能够滚动溢出父项的子项Use flexbox parent
One of advantages of using
margin: auto
compared tojustify-content: center
/align-items: center
is ability to scroll child item that is overflowing parentCSS
HTML
注意
此 CSS 类适用于几乎所有浏览器
CSS
HTML
Note
This CSS class work with almost all browsers