Search code examples
cssz-index

z-index normal div with flex div


I am trying to put a button on top of 4 blocks. Those blocks are inside divs with style display:flex.

But the style is not working on the button. Alse, if I give positive but less than the button to the blocks, the button hides under all the blocks.

I know I can give negative to the blocks, but in my project it will cause other problem. So I am wondering what's the best way to style them.

.block{
  flex:1;
  padding: 10px;
  border: 2px solid #666999;
  margin: 0 10px 10px 0;
}
#btn_box{
  margin-top: -20px;
  margin-bottom:-15px;
  z-index: 999;
  text-align: center;
}
#btn_box a{
  display: inline-block;
  background: #ff9999;
  padding: 5px 10px;
}
#btn_box + div{
  z-index: 1;
}

<div style='position:relative;'>
  <div style='display:flex;'>
    <div class='block'>1</div>
    <div class='block'>2</div>
  </div>

  <div id='btn_box'>
    <a>TestButton</a>
  </div>

  <div style='display:flex;'>
    <div class='block'>3</div>
    <div class='block'>4</div>
  </div>
</div>

See also here: https://jsfiddle.net/w4o8afts/

I have a workaround by making the button box a flex div, but it feels strange to do so.


Solution

  • Add position:relative

    #btn_box{
      position:relative;
      margin-top: -20px;
      margin-bottom:-15px;
      z-index: 999;
      text-align: center;
    }