user6822275 user6822275 - 14 days ago 6
CSS Question

CSS overlay over image background

I want to have an overlay over my image background, in order to see the white text above the image more clearly.

Why won't this solution work ?

HTML:

<div id="myDiv" class="bg1 image-cover">
<p>H</p>
</div>


CSS:

#myDiv {
width: 300px;
height: 300px;
color: #fff;
position: relative;
font-size: 100px;
font-weight: bold;
}

.image-cover:before {
content:'\A';
position: absolute;
width:100%;
height:100%;
top:0;
left:0;
background:rgba(0,0,0,0.9);
opacity: 1;
}

.bg1 {
background-size: cover;
background: url('https://2zpt4dwruy922flhqyznip50-wpengine.netdna-ssl.com/wp-content/uploads/2014/12/lock-and-stock-photos.jpg');
}


while this one does:

HTML:

<div id="myDiv" class="bg1">
<div class="image-cover">
<p>H</p>
</div>
</div>


CSS:

...

.image-cover {
content:'\A';
position: absolute;
width:100%;
height:100%;
top:0;
left:0;
background:rgba(0,0,0,0.9);
opacity: 1;
}

...


I think I am misunderstanding the way
:before
works, but I am not fan of the second solution as it has one more div than the first.

Answer

I'm glad you're already aware of the second solution; this tends to be the approach I normally use (though not for any particular reason). You can simply modify your original approach as follows and get the desired effect:

#myDiv > p {
  position: relative;
}

Namely, give the nested <p> tag a non-static position value. See here: CodePen

Comments