2016-10-03 59 views
1

我试图叠加两段文字,直接在另一个之上创建分层效果,同时也试图将它们垂直居中放在父项中。为了垂直居中,我使用了一个虚拟伪元素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>

FIDDLE

+0

叠加需要绝对定位......从这里开始。 –

+0

虽然绝对定位不允许垂直居中? –

+0

确定它会... –

回答

1

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>

+0

辉煌,这是完美的@Paulie_D。感谢你的帮助! –

0

垂直对齐:在表中小区1作品你不看跌期权。使用这个在你的风格可能它是帮助你

.bg-text { 
    color: green; 
    display: table-cell; 
    text-align: center; 
    vertical-align: middle; 
    width: 80%; 
} 

.text-wrapper { 
    color: blue; 
    display: table-cell; 
    text-align: center; 
    vertical-align: middle; 
    width: 80%; 
} 
figure { 
    background: red none repeat scroll 0 0; 
    float: left; 
    height: 100%; 
    overflow: hidden; 
    position: relative; 
    width: 100%; 
} 
+0

嗨,这有助于垂直对齐,但不允许它们叠加? –