我想要这篇文章的效果:http://css-tricks.com/text-blocks-over-image/
但我想知道在用 CSS 而不是 HTML 定义图像时如何做到这一点。
如果我创建一个比前一行长的新行,它会为两行创建一个与新行长度相同的背景颜色 block 。
实现此效果的正确方法是什么(无需在 HTML 中设置图像)?
===附加信息===
这是我之前尝试过的..
HTML:
<div class="img-main-wide">
<span class="img-text-green">
"be bold, and venture to be wise."<br />"Begin, be bold, and venture to be wise."
</span>
</div>
CSS:
.img-main-wide{
background-image: url(../images/Pyramids-Egypt.jpg);
max-width: 100%;
width: 100%;
height: 80%;
background-size: cover;
position: relative;
}
.img-text-green{
position: absolute;
margin-left: 1em;
top: 10em;
left: 0;
color: white;
padding-right: .5em;
padding-left: .5em;
background-color: rgba(51,102,0,0.8);
font-size: 36px;
font-style: oblique;
}
最佳答案
当您将 position: absolute
设置为 span
时,您隐式地将 display: block
设置为它。所以绝对定位的 span
不再像文本选择那样表现,而是像实心矩形一样表现。
要解决这个问题,您可以使用两个嵌套的 span
:外部的用于定位,内部的用于文本格式化。例如:
HTML:
<div class="img-main-wide">
<span class="img-text-green">
<span>
"be bold, and venture to be wise."<br />"Begin, be bold, and venture to be wise."
</span>
</span>
</div>
CSS:
/* .img-main-wide code is not changed */
.img-text-green {
position: absolute;
margin-left: 1em;
top: 10em;
left: 0;
}
.img-text-green > span {
color: white;
padding-right: .5em;
padding-left: .5em;
background-color: rgba(51,102,0,0.8);
font-size: 36px;
font-style: oblique;
}
另一种选择就是不使用 position: absolute
: fiddle
关于html - 如何仅使用 CSS 在图像上创建文本 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17916320/