Z-index: make element go under its parent's sibling

纵饮孤独 提交于 2020-01-14 09:33:19

问题


Imagine this DOM:

<header>
    <h1> header </h1>
    <!-- other elements -->
    <nav>
        nav
    </nav>
</header>

<div>
    content
</div>

Both header and nav are positioned as fixed. The content div is positioned as relative. I need to create a stack, with z-index, in this order (from top to bottom):

  • header *:not(nav)
  • content
  • nav

I'm having a hard time putting nav in the bottom (in other words, under its parent's sibling). I'm thinking that all header's children have to go either on top or under its sibling... is this right? If so, is there a workaround for this situation?


回答1:


Only content that is "positioned" such as position: absolute or position: fixed or position: relative will respect the z-index. As your HTML is structured, you can't do what you're asking for because parent/child is also respected so a child has to be in the parent (it can't be a completely different z-index vs. the parent). To do what you want, you will have to break the nav out of the header and then they can each have their own z-index, one above and one below the default zero z-index of content.




回答2:


The only workaround for this, with your DOM layout is to use negative z-index values. It is not highly recommend, though, to use negative value, just like its not recommended to use negative margin values.

A better solution would be to restructor your DOM. You may find this useful. It explains the recommended ways of use the z-index property.

Hope this helps you!



来源:https://stackoverflow.com/questions/14429728/z-index-make-element-go-under-its-parents-sibling

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!