htmlcsscss-positionz-indexabsolute

Putting elements between background and content on the site


I have the following layout:

<div class="bg">
  <div class="header">
    <h1>Hello World!</h1>
  </div>
</div>
.bg{
  background: green;
}
.header{
  height: 500px;
}

My goal: add elements(ellipses) behind the header's content by z axis. (see design photo)

Design Photo

This ellipses should be positioned absolute

I tried to this:

<div class="bg">
        <div className="ellipse"></div>
        <div class="header">
          <h1>Hello World!</h1>
        </div>
</div>

Then, I positioned .ellipse absolute and gave it z-index: 0, and z-index:1 for .header. Actually, .ellipse is position: absolute, but .header is static. It didn't produce the expected result


Solution

  • You have to set the position of the bg and header elements other then static to be able to use the z-index. You can read about it here.

    I've also adjusted the code a bit to mach the image you provided.

    .bg {
          position: relative;
          background: #e2ede9;
        }
    
        .ellipse {
          position: absolute;
          top: 10%;   /* Adjust these values */
          left: -15%;  /* Adjust these values */
          width: 300px;  /* Or the desired size of your ellipse */
          height: 300px; /* Or the desired size of your ellipse */
          background: #cfe3dc; /* Or the desired color of your ellipse */
          border-radius: 50%;
          z-index: 0;
          transform: translate(-10%, -10%); /* to center the ellipse */
        }
    
        .header {
          position: relative;
          z-index: 1;
          height: 500px;
          padding: 100px;
        }
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <div class="bg">
        <div class="ellipse"></div>
        <div class="header">
          <h1>Hello World!</h1>
        </div>
      </div>
    </body>
    </html>