因此,以下代码可以实现“my-container”背景图像的不透明度,而不会影响“h1”的不透明度,这是所需的结果。
HTML:
<div class="my-container">
<h1>Scotch Scotch Scotch</h1>
</div>
CSS:
.my-container {
position: relative;
background: #5C97FF;
overflow: hidden;
}
/* You could use :after - it doesn't really matter */
.my-container:before {
content: ' ';
display: block;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 1;
opacity: 0.6;
background-image: url('http://placekitten.com/1500/1000');
background-repeat: no-repeat;
background-position: 50% 0;
-ms-background-size: cover;
-o-background-size: cover;
-moz-background-size: cover;
-webkit-background-size: cover;
background-size: cover;
}
有关此代码的一些问题:
为什么在.my-container类中需要'overflow:hidden'?
我发现如果我更改或删除'.my-container:before'中的任何属性 - 值对,那么背景图像根本就不会显示。具体为什么'内容'需要设置为''? 为什么宽度和高度都有值?这需要是%吗?
谢谢
答案 0 :(得分:1)
您可以向z-index
h1
.my-container {
position: relative;
background: #5C97FF;
overflow: hidden;
}
.my-container:before {
content: ' ';
display: block;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 1;
opacity: 0.6;
background-image: url('http://placekitten.com/1500/1000');
background-repeat: no-repeat;
background-position: 50% 0;
-ms-background-size: cover;
-o-background-size: cover;
-moz-background-size: cover;
-webkit-background-size: cover;
background-size: cover;
}
h1 {
position: relative;
z-index: 2;
}
&#13;
<div class="my-container">
<h1>Scotch Scotch Scotch</h1>
</div>
&#13;
答案 1 :(得分:1)
回答你的问题:
答案 2 :(得分:0)
你可以这样做:
.my-container {
position: relative;
background: #5C97FF;
overflow: hidden;
background-image: url('http://placekitten.com/1500/1000');
background-repeat: no-repeat;
background-position: 50% 0;
-ms-background-size: cover;
-o-background-size: cover;
-moz-background-size: cover;
-webkit-background-size: cover;
background-size: cover;
}
div.mask{
background-color:#5C97FF64;
width:100%;
height:100%;
padding: 20px 0;
}
h1{margin:0;}
&#13;
<div class="my-container">
<div class="mask">
<h1>Scotch Scotch Scotch</h1>
</div>
</div>
&#13;