我試圖疊加兩段文字,直接在另一個之上創建分層效果,同時也試圖將它們垂直居中放在父項中。爲了垂直居中,我使用了一個虛擬僞元素in this post,我發現這是在居中放置高度可變的父母時最可靠的方法。疊加2文本元素,雖然垂直居中
正如您在下面的提琴中可以看到的那樣,.bg文本元素是垂直居中的,但是.text-wrapper元素被強制放在父元素的下面,所以看起來這種垂直居中的方法不允許多於一個居中元素?
figure {
position: relative;
overflow: hidden;
float: left;
width: 100%;
height: 200px;
background: red;
}
figure::before {
content: "[BEFORE]";
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em;
}
/* Background text */
.bg-text {
display: inline-block;
vertical-align: middle;
width: 80%;
color: green;
text-align: center;
}
/* Text */
.text-wrapper {
display: inline-block;
vertical-align: middle;
width: 80%;
text-align: center;
color: blue;
}
<figure>
<div class="bg-text">BACKGROUND TEXT</div>
<div class="text-wrapper">
<h3>Overlay This</h3>
<h4>And this!</h4>
</div>
</figure>
疊加需要絕對定位......從這裏開始。 –
雖然絕對定位不允許垂直居中? –
確定它會... –