【发布时间】:2015-10-07 14:04:22
【问题描述】:
this article 提到了一种使用“幽灵元素”在 css 中垂直居中元素的技术。
/* This parent can be any width and height */
.block {
text-align: center;
/* May want to do this if there is risk the container may be narrower than the element inside */
white-space: nowrap;
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
}
但是,当要居中的元素有width:100% 时,它不起作用,因为元素被推到了新行上。您如何调整解决方案以便在这种情况下工作?我需要一个具有良好浏览器支持的解决方案,包括 IE9+
【问题讨论】:
-
我特别需要这个解决方案是有原因的。另外,我相信您在链接中提出的“未知高度和宽度的元素的水平和垂直方向”的解决方案是不理想的,因为它can cause elements to become blurred due to sub-pixel rendering
-
秋千和环形交叉路口...您付钱,您可以选择。祝你好运。
-
您是在使用 :before 而不是 ::before,还是只是问题中的拼写错误?
-
啊!我正在这样做,但即使你只使用一个冒号也可以。
标签: css alignment vertical-alignment