How to overlay divs properly?

here’s the code : https://codepen.io/Abdou_dz_23/pen/GaGbWX?editors=1100

what i’m trying to achive :

  • < section > has a background
  • on top of it theres an overlay div , color yellow , and has 0.4 opacity
  • on top of all of this comes my .content div (highest z-index) , text color must be white and un-affected by the yellowish overlay div color

the problem ?
the text color is yellowish , wich means it’s actually below, not above the overlay div

how can i achive this ?

Add position: relative; to .content

2 Likes

Hi! So the trick here is that you can only set a z-index on elements that are positioned.

Because you’re not overtly setting the position of your ‘.content’ div, it’s defaulting to position: static, which doesn’t allow it to take the z-index you’re giving it.

You’ve got to give it a position: relative.

2 Likes

You can get the text to be white by doing this.

  1. Set the p tag to color: white.
  2. Make the .content div width: 100%, height: 100%, and a background color of yellow.
.overlay{
  z-index:2;
  height:100%;
  width:100%;
  opacity:0.4;
  position:absolute;
}
.content {
  z-index:3;
  height:100%;
  width:100%;
  background: hsla(54, 100%, 50%, 0.45);
}
.content p {
  color: #FFFFFF;
}
2 Likes
.content {
  z-index: 3;
  position: relative;   <--- add this
}

uhm., yeah. everyone has already said this., but let me take it a step further.

if you want your .section to be below everything,. it’s better to give it a z-index: -1000.
then you can give the .overlay a z-index: -500

Then every new element you make doesn’t require a z-index.

However, if you stick to the approach of using a positive z-index to .section & .overlay it now forces you to add a z-index to every new div,. that you want on top.

2 Likes

Just what i needed, thank you

exactly, this is the little piece i was missing, they have to be positioned ! thank u

well, it works yea, that overlay div is useless now, the use of it was adding a shade of yellow to the page, so i stacked divs.
But i guess that’s another way to do it, just using a background color with hsla to make it show what’s beneath it .

1 Like

@Simply_abdou yes my brother, there are multiple ways to approach it.
There is another way which uses only one div and background: with multiple arguements like this
HTML:

<article></article>

CSS:

article {
    width: 100%;
    height: 100%;
    background: linear-gradient(transparent, hsla(255, 10%, 10%, 1), hsla(255, 10%, 0%, 1)),
    url(images/foreground-with-transparency.png), 
    url("images/background-pattern.png");
}

/*
element {
    width: 100%;
    height: 100%;
    background: linear-gradient(top_layer_with_transparency),
    url(middle_layer),
    url(bottom_layer);
}
*/

The linear gradient using hsla is the top layer, in the middle layer is a PNG with transparency, and the layer in back another image.

Here is an CODEPEN EXAMPLE .