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+
最佳答案
我想通了,我正在遭受“空内联 block 元素之间的间距问题”的困扰。有几种方法可以解决这个问题,我通过注释掉 HTML 中元素之间的空格来解决这个问题。 Here is a working plunker
关于css - 使用 'ghost element' 在其容器内垂直对齐宽度为 100% 的内联 block 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31482795/