gpt4 book ai didi

html - 覆盖 2 个文本元素,同时垂直居中

转载 作者:行者123 更新时间:2023-11-28 16:02:30 24 4
gpt4 key购买 nike

我试图将两段文本直接叠加在一起以创建分层效果,同时还尝试将它们垂直居中放置在父文本中。为了垂直居中,我使用了一个 ghost 伪元素,如下所述 in this post ,我发现这是在高度可变的父项中居中时最可靠的方法。

正如您在下面的 fiddle 中看到的那样,.bg-text 元素是垂直居中的,但是 .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>

FIDDLE

最佳答案

Flexbox 和绝对定位可以做到这一点:

* {
margin: 0;
padding: 0;
}
figure {
position: relative;
height: 200px;
background: red;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
}
/* Background text */

.bg-text {
width: 80%;
color: green;
text-align: center;
}
/* Text */

.text-wrapper {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 255, 0, 0.25);
width: 80%;
text-align: center;
color: blue;
}
<figure>
<div class="bg-text">BACKGROUND</div>
<div class="text-wrapper">
<h3>Overlay This</h3>
<h4>And this!</h4>
</div>
</figure>

关于html - 覆盖 2 个文本元素,同时垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39829167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com