Search code examples
htmlcssz-index

Position a non-fixed div above a fixed div?


Is there a way to position a non-fixed div that scrolls with the page above a fixed div? I tried z-index but that doesn't work. The fixed div has a box inside that has a layout based on the parent wrapper's width percentage. Below is my code and jsfiddle. I would like the red box that's fixed to be below the blue box that scrolls.

HTML

<div class="holder">
  <div class="wrapper">
    <div class="redbox">
      <p>
      red box
      </p>
    </div>
  </div>
</div>

<div class="bluebox">
  <p>
  blue box
</div>

CSS

body, html {
  height: 1000px;
  margin: 0;
  padding: 0;
}

.holder {
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
}

.wrapper {
  width: 80%;
  margin: 50px auto 0 auto;
}

.redbox {
  width: 100px;
  height: 100px;
  background: red;
}

.bluebox {
  width: 500px;
  height: 500px;
  margin: 75px 0 0 0;
  background: blue;
}

jsfiddle


Solution

  • In Short: You need to add position: relative to the .bluebox class, to add it to the same stack-context as the fixed one.

    W3Schools says:

    Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky).

    This is related to the so called stack-context in a web page. As noted in the MDN web docs the stack context order is as:

    • Root element of the document ().
    • Element with a position value absolute or relative and z-index value other than auto.
    • Element with a position value fixed or sticky (sticky for all mobile browsers, but not older desktop).
    • Element that is a child of a flex (flexbox) container, with z-index value other than auto.
    • Element that is a child of a grid (grid) container, with z-index value other than auto.
    • Element with a opacity value less than 1 (See the specification for opacity).
    • Element with a mix-blend-mode value other than normal.
    • Element with any of the following properties with value other than none: transform filter perspective clip-path mask / mask-image / mask-border
    • Element with a isolation value isolate.
    • Element with a -webkit-overflow-scrolling value touch.
    • Element with a will-change value specifying any property that would create a stacking context on non-initial value (see this post).
    • Element with a contain value of layout, or paint, or a composite value that includes either of them (i.e. contain: strict, contain: content).