【问题标题】:Darken image overlay and add text over it in CSS使图像叠加变暗并在 CSS 中在其上添加文本
【发布时间】:2014-11-26 12:08:46
【问题描述】:
我将如何变暗(添加半透明叠加层)并向该图像添加文本(但水平和垂直居中),如下所示:
HTML
<img src="http://luxurylaunches.com/wp-content/uploads/2014/05/uber-london.jpg" id="top" data-appear-animation="fadeIn">
CSS
#top {
width: 100%;
height: auto;
}
body {
margin: 0px;
}
在这里提琴:http://jsfiddle.net/6jf0nxd5/
【问题讨论】:
标签:
html
css
overlay
transparency
【解决方案1】:
要使文本水平和垂直居中,您需要将其包装在带有text-align:center; 的容器中。然后您可以使用伪元素将其垂直居中。对于叠加层,你可以给文本容器一个rgba() 可以有透明度的背景颜色:
DEMO
body {
margin: 0px;
}
.wrap{
position:relative;
}
.wrap img{
width:100%;
height:auto;
display:block;
}
.text{
position:absolute;
top:0; left:0;
width:100%; height:100%;
background:rgba(255,255,255,.5);
text-align:center;
}
.text:after{
content:'';
width:1px; height:100%;
vertical-align:middle;
display:inline-block;
}
.text span{
display:inline-block;
vertical-align:middle;
}
<div class="wrap">
<img src="http://luxurylaunches.com/wp-content/uploads/2014/05/uber-london.jpg" id="top" data-appear-animation="fadeIn" />
<div class="text"><span>Text over the image
<br/>Second line</span></div>
</div>
【解决方案2】:
html
<div id='back'><div id='mask'><div id='text'>fsfsfsssf</div></div></div>
css
body{
margin:0px;
}
#back{
width:100%;
height:500px;
background: url("http://luxurylaunches.com/wp-content/uploads/2014/05/uber-london.jpg") no-repeat;
background-size:contain;
}
#mask{
position:relative;
width:100%;
height:500px;
background:rgba(255,255,255,0.5);
}
#text{
position:absolute;
top:230px;
left:48%;
}
小提琴:http://jsfiddle.net/6jf0nxd5/20/
【解决方案3】:
试试这个
HTML:
<img src="http://luxurylaunches.com/wp-content/uploads/2014/05/uber-london.jpg" id="top" data-appear-animation="fadeIn">
<div class="sometext">some text</div>
CSS:
#top {
width: 100%;
height: auto;
opacity:.3;
position:absolute;
z-index:0;
}
body {
margin: 0px;
}
.sometext {
position:absolute;
z-index:1;
}
【解决方案4】:
http://jsfiddle.net/6jf0nxd5/21/
HTML
<div class='imgWrap'>
<span>This is some very long text that might or might now flow on top of the image</span>
<img src="http://luxurylaunches.com/wp-content/uploads/2014/05/uber-london.jpg" id="top" data-appear-animation=fadeIn">
</div>
CSS
.imgWrap{
display:inline-block;
background:#000;
position:relative;
}
.imgWrap > img{ display:block; opacity:.5; }
.imgWrap > span{ position:absolute; display:table; text-align:center; z-index:1; height:100%; left:0; right:0; padding:20px; color:#FFF; font-size:2em; }
.imgWrap > span::after{ content:attr(data-title); display:table-cell; vertical-align: middle; }