鬼元素技術(Micha Czernows hack)
即使容器的尺寸未知,此技術也可以使用。
在容器內設定一個 ghost
元素,使其居中,高度為 100%,然後在那個和要居中的元素上使用 vertical-align: middle
。
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 element */
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
/* There is a gap between ghost element and .centered,
caused by space character rendered. Could be eliminated by
nudging .centered (nudge distance depends on font family),
or by zeroing font-size in .parent and resetting it back
(probably to 1rem) in .centered. */
margin-right: -0.25em;
}
/* The element to be centered, can also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
white-space: normal; /* Resetting inherited nowrap behavior */
}
HTML
<div class="block">
<div class="centered"></div>
</div>