Home > OS >  CSS Position background element to cover parents/parent
CSS Position background element to cover parents/parent

Time:07-11

How can I make the green background to cover all the .section class?

I have this section->container->elements relation everywhere and I would like to define a "background" element that covers the whole section.

There is possible to have multiple sections each with it's own background.

.section {
  width: 100%;
  background-color: yellow;
}

.container {
  height: 300px;
  padding: 30px;
  margin: 100px;
  background-color: red;
}

.background {
  width: 100%;
  height: 100%;
}

.red {
  background: red;
}

.green {
  background: green;
}
<div >
  <div >
    <div  />
    <div>
      some content
    </div>
  </div>
</div>

enter image description here

CodePudding user response:

you Should style give tag section

background-color: green;

CodePudding user response:

You could set the position of .section to relative, and set the position of .green to absolute.

Now the position, width & height will use .section as reference.

Then you could set these properties freely.

here is the code:

.section{
  position: relative;
}

.green {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

and then you may have to adjust their z-index

.green {
  z-index: -1;
}

.section {
  z-index: 0;
}

absolute: The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left. MDN

  •  Tags:  
  • css
  • Related