Reputation: 153
I have a very simple CSS question that I can't answer myself for some reason. I have a header that I'd like to add a black transparent background to it. Here is my HTML:
<div id="directory">
<div class="headerbg"></div>
<h1>Rental Directory</h1>
</div>
The .headerbg has the black transparent background. But for some reason the H1 is layered underneath the black background. I tried z-indexing both the background or the h1 but I still can't get the H1 to stack on top of the background. Can someone please advise? Thank you.
Here is a link to the JS Fiddle: https://jsfiddle.net/x1L2jxnx/1/
Upvotes: 1
Views: 5095
Reputation: 4126
Adding .headerbg div
just for a background effect isn't the ideal way of coding the web.
I've removed the .headerbg div
from the markup and added a css pseudo element
to fix that issue. Like this.
#directory { padding: 10px 0 10px 20px; position: relative; height: 35vh; background-image: url('https://markshimazuphotography.files.wordpress.com/2013/05/san_diego_skyline_coronado_sunset.jpg'); background-repeat: no-repeat; color: #fff;}
#directory::after {content: ''; background-color: rgba(0,0,0,0.5); width: 40em; height: 8em; position: absolute; top: 10px; left: 0; }
h1 { position: absolute; font-size: 50px; border-bottom: 15px solid #e8cd54; z-index: 1}
<div id="directory">
<h1>
Rental Directory
</h1>
</div>
I've also added position in the h1
element. Since the parent div
is position: relative
and the pseudo element
is too I had to give the h1
so as I could set z-index: 1
to it as explained by @CBroe in your commments.
Upvotes: 0
Reputation: 56
It is an issue with your absolute positioning.
h1 {
font-size: 50px;
border-bottom: 15px solid #e8cd54;
width: 100%;
position: absolute;
}
Replace the h1 with this code.
Upvotes: 2
Reputation: 11086
z-index works fine for absolute positioned elements.
Or you may simply nest the h1 inside the headerbg.
#directory { padding: 10px 0 10px 20px; position: relative; height: 35vh; background-image: url('https://markshimazuphotography.files.wordpress.com/2013/05/san_diego_skyline_coronado_sunset.jpg'); background-repeat: no-repeat; color: #fff;}
.headerbg { background-color: rgba(0,0,0,0.5); width: 40em; height: 8em; position: absolute; top: 10px; left: 0; z-index:1}
h1 { position:absolute;left:10px;top:10px;z-index:2;font-size: 50px; border-bottom: 15px solid #e8cd54; }
<div id="directory">
<div class="headerbg"></div>
<h1>
Rental Directory
</h1>
</div>
Upvotes: 1
Reputation: 13431
z-index
works for positioned absolute
or relative
elements, it's simple just add position relative and z-index for h1 tag,
h1 { font-size: 50px; border-bottom: 15px solid #e8cd54; position:relative; z-index:1 }
Upvotes: 1
Reputation: 471
I believe you're placing the H1 tags outside out side the headerbg div. Try placing h1 inside the headerbg div like this:
<div class="headerbg">
<h1>Rental Directory</h1>
</div>
Upvotes: 0