简体   繁体   English

如何使文本显示在背景图像的顶部?

[英]How do I make text appear on top of background image?

I have used this approach https://stackoverflow.com/a/22211990 我已经使用了这种方法https://stackoverflow.com/a/22211990

Only problem is that as soon as I enter text/content in div like this: <div>abc</div> 唯一的问题是,一旦我在div中输入文本/内容,就象这样: <div>abc</div>

That text appear under the image. 该文本出现在图像下方。

Code: https://codepen.io/labeeb/pen/JMxzQY 代码: https//codepen.io/labeeb/pen/JMxzQY

 * { padding: 0px; margin: 0px; } .image { background: url('https://i.pinimg.com/originals/4f/d6/ef/4fd6ef1f078ca5e229ce5925c10f194a.jpg') no-repeat; background-size: 100%; background-size: contain; height: 0; padding-top: 100.44%; /* (bg image width/ bg image height) * 100*/ } 
 <div class="image">aaa</div> 

You can give the image element position:relative and wrap the text in an element with position:absolute and top:0 您可以将图片元素指定为position:relative然后将文本包装在一个具有position:absolutetop:0的元素中

 *{ padding:0px; margin:0px; } .relative { position:relative; } .text { position: absolute; color: red; top:0; } .image{ background:url('https://i.pinimg.com/originals/4f/d6/ef/4fd6ef1f078ca5e229ce5925c10f194a.jpg') no-repeat; background-size:100%; height:0; padding-top:100.44%; /* (bg image width/ bg image height) * 100*/ } 
 <div class="image relative"> <div class="text">aaa</div> </div> 

For me : you choice is a bad strategy, because de the padding-top will always impact your content. 对我来说:您的选择是一个错误的策略,因为填充顶部总是会影响您的内容。 It is not the background job. 这不是后台作业。

My solution : combine height 100vh and background-size cover. 我的解决方案:结合高度100vh和背景大小的封面。

 *{ padding:0px; margin:0px; } .image{ color: white; height: 100vh; background:url('https://i.pinimg.com/originals/4f/d6/ef/4fd6ef1f078ca5e229ce5925c10f194a.jpg') no-repeat; background-size:cover; } 
 <div class="image">aaa</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM