2016-10-03 63 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

嗨,這有助於垂直對齊,但不允許它們疊加? –