2017-09-26 78 views
0

我正在按照以下解決方案給出的解決方案:如何疊加圖像上的文本,使用relativeabsolute定位。問題是,與position: absolute文本彈出其容器,去盡topright如何在容器中的圖像上疊加文本 - 並將文本保留在容器中

我很樂意使用背景圖片,但我需要技巧來獲得容器相匹配圖像的大小,我不知道如何讓它變得流暢。

看起來像一個非常簡單的問題,人們總是在尋找解決方案。也可以將文字疊加在不透明的圖像上,並需要使用:after。希望有這些情況的直截了當的選擇。

.container { 
 
    margin: 0 10%; 
 
} 
 
.container img { 
 
    position: relative; 
 
    width: 100%; 
 
} 
 

 
#div1 .text { 
 
    position: absolute; 
 
    bottom: 0; 
 
    right: 0; 
 
} 
 

 
#div2 .text { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
}
<div id="div1" class="container"> 
 
    <img src="http://placehold.it/800x200" /> 
 
    <div class="text"> 
 
    <h3>Top Image</h3> 
 
    <p>This text should be in the bottom right of the top image.</p> 
 
    </div> 
 
</div> 
 

 
<div><p>A bunch of miscellaneous text here.</p></div> 
 

 
<div id="div2" class="container"> 
 
    <img src="http://placehold.it/800x200" /> 
 
    <div class="text"> 
 
    <h3>Lower Image</h3> 
 
    <p>This should be in the top left of the lower image.</p> 
 
    </div> 
 
</div>

回答

2

您需要設置position:relative.container這是.text正確的容器。請注意,img.text,而不是它的容器的兄弟。

.container { 
 
    margin: 0 10%; 
 
    position: relative; 
 
} 
 
.container img { 
 
    width: 100%; 
 
} 
 

 
#div1 .text { 
 
    position: absolute; 
 
    bottom: 0; 
 
    right: 0; 
 
} 
 

 
#div2 .text { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
}
<div id="div1" class="container"> 
 
    <img src="http://placehold.it/800x200" /> 
 
    <div class="text"> 
 
    <h3>Top Image</h3> 
 
    <p>This text should be in the bottom right of the top image.</p> 
 
    </div> 
 
</div> 
 

 
<div><p>A bunch of miscellaneous text here.</p></div> 
 

 
<div id="div2" class="container"> 
 
    <img src="http://placehold.it/800x200" /> 
 
    <div class="text"> 
 
    <h3>Lower Image</h3> 
 
    <p>This should be in the top left of the lower image.</p> 
 
    </div> 
 
</div>

+0

臨屋非常好的解釋! – abalter

0

我不太相信有足夠的信息。我假設你的容器寬800px,高200px(如果你的容器增加了高度,我使用了最小高度)。如果你能提供這將是巨大的更具體信息(也有使用對象的位置屬性(等)更復雜的方式,使這個有點「聰明」。

img { 
    max-width: 100%; 
    display: block; 
    height: auto; 
} 

.container { 
    position: relative; 
    min-height: 200px; 
    width: 800px; 
    margin: 0 10%; 
} 

.container img { 
    z-index: 500; 
    top: 0; 
    left: 0; 
} 

.container .text { 
    position: absolute; 
    z-index: 1000; 
} 

#div1 .text { 
    bottom: 0; 
    right: 0; 
} 

#div2 .text { 
    position: absolute; 
    top: 0; 
    left: 0; 
} 
相關問題