DEV Community

Cover image for CSS child behind parent with z-index
Sabbir Sobhani
Sabbir Sobhani

Posted on β€’ Edited on

9

CSS child behind parent with z-index

z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements). w3school

Child behind Parent

parent: Not set any z-index (it's important), set position relative (by default though it's relative).

child: Give any positional value (absolute, sticky or fixed), and z-index any negative integer value.

Now, the child is behind the parent element. βœ…

βž•

Scenario

  1. If you have a situation so to make the parent element fixed, sticky or absolute then what?

Simple, since child element will not work with z-index: -1; or behind parent, if parent is other than relative. Just wrap the parent element with any tag and make it fixed, sticky or absolute.

<div class="wrapper fixed-or-sticky-or-absolute"> πŸ‘ˆwrapper tag
    <div class="parent relative">
        <div class="child any-position-will-work z-index(-1)"></div>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Moreover, you can now give any z-index value to the wrapper element tag and it will not affect the child and parent.

Done.

Buy Me a Coffee πŸ™:
If this article helped you a bit and you'd like to support my work, feel free to buy me a coffee: https://buymeacoffee.com/sobhani β˜•οΈ Thanks for keeping me motivated!

Follow me on Twitter sabbirsobhani

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (2)

Collapse
 
architchandra profile image
Archit Chandra β€’

I was facing a problem where this exact fix helped me. Why is it important to omit the z-index from the parent? Can you also add a reference to the documentation where this is mentioned? Thanks.

Collapse
 
sabbirsobhani profile image
Sabbir Sobhani β€’

Good to know it helps!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay