Home > OS >  Need help understanding the stacking layer order of this code that uses the z-index
Need help understanding the stacking layer order of this code that uses the z-index

Time:01-21

I am working on this project and have a question about this code stacking order. It has a z-index -1, background color, a background image of linear gradient and a background image of an image. I can't understand the layering involved in it.

What is the order of the positioning? Which ones are closer to the viewer and which ones are further away?

The code looks like this:

body::before {
    content:"";
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    z-index: -1;
    background: var(--darkblue);
    background-image: linear-gradient(
        to right,
        rgba(58,58,158,0.8),
        rgba(136,136,206, 0.7)
      ),
      url(images/image.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
}

CodePudding user response:

Since you mentioned z-index:-1, background and background-image all are on'-1' layer.

A better way to add color to background image is using 'linear-gradient' with 'background-image' property but using background with background-image like so,

background: var(--darkblue);
background-image: linear-gradient(
    to right,
    rgba(58,58,158,0.8),
    rgba(136,136,206, 0.7)
  ),
  url(images/image.jpg);

is useless.

And if you still want to use both, you can put them in diff 'divs'.

CodePudding user response:

For the layering order for a HTML page, it will always have the following rules.

  • An element will always be in front of it's parent. This does not say anything about other elements inside it.
  • The CSS engine will always render higher z-indexes on front of lower z-indexes. If the z-index is not defined, it will act as being 0.
  • The elements will render static elements first, then relative, then absolute, then fixed.
  • If none of these rules are different, the elements will render on the order as written (first one on background, latest one on foreground).

For layering background images, the first one will render on the foreground and the latest one on the background. The background color will always render before the background image.

  •  Tags:  
  • Related