Why using absolute position causes the div to be on top?

后端 未结 3 830
庸人自扰
庸人自扰 2020-12-04 03:27

Please see this very simple snippet to illustrate my question below:

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 04:25

    Try following. Add style for h1 as follows

    #container {
      position: relative;
      padding: 20px;
      border: 2px solid gray;
    }
    
    #back {
      position: absolute;
      top: 0;
      bottom: 50%;
      left: 0;
      right: 0;
      background-color: #bbb;
    }
    #container h1 {
      position : relative;
      z-index: 1;
    }

    Some Text

    static elements do not have a z-index, however, the others default to 0 that is why it stays at the bottom most layer of html and the non-static element covers it. If you wish to show them above, set the position of static elements to relative and give any positive z-index value.

提交回复
热议问题