Search code examples
htmlcssz-indexjscrollbar

Z-index doesn't work with overlapping a parent DIV with one inside it


What I am trying to do is to hide the scrollbar of a DIV. In order to do that, I created an outer DIV with overflow-y: hidden; and placed a slightly wider DIV inside it. I gave the outer DIV higher z-index than the inner one. Both have position: fixed;, but no matter what, it doesn't work – the wider DIV is still visible outside its parent DIV. I also made it so that z-index of html would be higher than that of the inner DIV, in hopes it would hide the scrollbar, but that didn't work either. Neither did using negative z-index work. I've searched for days for a fix to this but none worked.

Here is the basic example code(should I include the entire code in jsfiddle?) - HTML:

<html>
    <body bgcolor="#BFBFBF">
       <div class="outer_MB">
          <div class="in_MB">
          </div>
       </div>
    </body>
</html>

CSS:

html {
    z-index: 2;
}

.outer_MB {
    position: fixed;
    height: 70%;
    width: 84%;
    left: 8%;
    bottom: 0;
    border-left: 1px solid black;
    border-right: 1px solid black;
    overflow-y: hidden;
    z-index: 2;
    text-align: center;
}

.in_MB {
    height: 70%;
    width: 86%;
    position: fixed;
    overflow-y: scroll;
    z-index: 1;
}

PM: This is the first question I asked on this website, so tell me if I'm missing something and I'll try to fix it.


Solution

  • The problem is that your .in_MB element is tied to the outer_MB element. No matter what your inner element's z-index is set to, it will always display on top of the outer element.

    Imagine having two boxes. A large box and a small box. You place the small box inside the large box. You then lift the large box up - the small box doesn't stay where it is, it lifts with the large box.

    If you want .in_MB to appear behind .outer_MB, you'll need to make them separate elements:

    <div class="outer_MB"></div>
    <div class="in_MB"></div>
    

    You'll then need to style the .in_MB element to appear in the same position as the .outer_MB element. As these elements are now separate but share the same overall ancestor, the z-index will kick into action accordingly.