Home > Software engineering >  Div is still hidden after added z-index
Div is still hidden after added z-index

Time:06-13

I have simply following html css code:

Someone knows why div with button is still hidden? I added z-index

function myFunction() {
  console.log('Clicked')
}
div{
  color: yellow;
  position: relative;
  z-index: 1000;
}

div:after{
  content: '';
  background: red;
  padding: 100px;
  position: absolute;
  left: 0;
  z-index: 999;
}
<div>
<button onclick="myFunction()">Click me</button>
</div>

CodePudding user response:

Instead of giving the z-index to your div (which :after is still a part of, and therefore positioned over your div) give it to the button:

function myFunction() {
  console.log('Clicked')
}
div button{
  color: yellow;
  position: relative;
  z-index: 1000;
}

div:after{
  content: '';
  background: red;
  padding: 100px;
  position: absolute;
  left: 0;
  z-index: 999;
}
<div>
<button onclick="myFunction()">Click me</button>
</div>

Generally speaking, you should probably not style your :after and your div with two seperate z-index. Rather Create a new div an style them seperately.

function myFunction() {
  console.log('Clicked')
}
div{
  background: red;
  padding: 100px;
  position: absolute;
  left: 0;
  z-index: 999;
}
<div>
<button onclick="myFunction()">Click me</button>
<p>Test</p>
<p>Test</p>
</div>

CodePudding user response:

Your :after element is in front of the button.

Try position: relative and z-index: 1 on the button and z-index: 0 on the :after element.

CodePudding user response:

For z-index to put div:after element behind its parent, use negative value. It is deflecting from normal behaviour but specs say so https://www.w3.org/TR/CSS21/visuren.html#layers

function myFunction() {
  console.log('Clicked')
}
div{
  color: yellow;
  position: relative;
}

div:after{
  content: '';
  background: red;
  padding: 100px;
  position: absolute;
  left: 0;
  z-index: -1;
}
<div>
<button onclick="myFunction()">Click me</button>
</div>

CodePudding user response:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div{
  color: rgb(238, 17, 17);
  position: relative;
  z-index: -1;
}

div:after{
  content: '';
  background: red;
  padding: 100px;
  position: absolute;
  left: 0;
  z-index: -1;
}
  </style>
</head>
<body>
  <div>
 
    <button type="button" onclick="myFunction()">Click Me!</button>
    </div>
    <script>
    function myFunction() {
      console.log('Clicked')
    }
  </script>
</body>
</html>

  • Related