Using z-index to get div above another div

前端 未结 4 1859
囚心锁ツ
囚心锁ツ 2020-11-28 16:00

I want the div1 to be above div2. I try with z-index but it does not work.

I\'ve tried this code:

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 16:46

    You can add position: relative to both divs and create stacking context

    div {
      width:100px;
      height: 100px;
    }
    
    .div1 {
      background: red;
      z-index: 2;
      position: relative;
    }
    
    .div2 {
      background: blue;
      margin-top: -15vh;
      z-index: 1;
      position: relative;
    }

    Or you could use transform-style: preserve-3d; so now .div1 should be positioned in the 3D-space and not flattened in the plane.

    div {
      width:100px;
      height: 100px;
    }
    
    .div1 {
      background: red;
      z-index: 2;
      transform-style: preserve-3d;
    }
    
    .div2 {
      background: blue;
      margin-top: -15vh;
      z-index: 1;
    }

    You can also use some random transform like translate or rotate

    div {
      width:100px;
      height: 100px;
    }
    
    .div1 {
      background: red;
      z-index: 2;
      transform: translate(1px);
    }
    
    .div2 {
      background: blue;
      transform: translate(1px, -15vh);
      z-index: 1;
    }

    Filters also work but they have bad Support

    div {
      width:100px;
      height: 100px;
    }
    
    .div1 {
      background: red;
      filter: brightness(0.4);
      z-index: 2;
    }
    
    .div2 {
      background: blue;
      margin-top: -15vh;
      filter: brightness(0.4);
      z-index: 1;
    }

提交回复
热议问题