hirantha129
hirantha129

Reputation: 619

Relative positioned content goes above sticky positioned header

Have a look at following code snippet.

<div class="container">
    <div class="header" style="position:sticky;top:0">
        Header
    </div>
    <div class="content" style="position:static">
        Page content
        ...
    </div>
</div>

Here while scrolling page down, content goes below the header. All work as expected.

But if I change 'content' div positioning to relative, content starts to goes over the sticky header while scrolling page.

Why this happens? Is there a solution for this without using z-index?

Upvotes: 4

Views: 1988

Answers (2)

Klick_99
Klick_99

Reputation: 1

One option that can help solve the problem without using z-index is to use display:order. In this solution header has higher priority becouse it rendering after page content

<div class="container" style="display: flex">
    <div class="content" style="position:static">
        Page content
        ...
    </div>
    <div class="header" style="position:sticky;top:0;order:-1;">
        Header
    </div>
</div>

Upvotes: 0

Son Dang
Son Dang

Reputation: 1

The stacking order refers to the order in which elements are painted on the screen along the z-axis. Elements with a higher stacking order are painted on top of elements with a lower stacking order.

According to the stacking order, this issue occurs when the div.relative has a higher stacking order than the div.sticky (the div.sticky appears before the div.relative in html). There is no solution without z-index.

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_positioned_layout/Understanding_z-index/Stacking_without_z-index

Upvotes: 0

Related Questions