CSS: How to position two elements on top of each other, without specifying a height?

后端 未结 9 1286
走了就别回头了
走了就别回头了 2020-12-22 21:37

I have two DIVs that I need to position exactly on top of each other. However, when I do that, the formatting gets all screwed up because the containing DIV acts like there

9条回答
  •  佛祖请我去吃肉
    2020-12-22 22:13

    Actually this is possible without position absolute and specifying any height. All You need to do, is use display: grid on parent element and put descendants, into the same row and column.

    Please check example below, based on Your HTML. I added only and some colors, so You can see the result.

    You can also easily change z-index each of descendant elements, to manipulate its visibility (which one should be on top).

    .container_row{
      display: grid;
    }
    
    .layer1, .layer2{
      grid-column: 1;
      grid-row: 1;
    }
    
    .layer1 span{
      color: #fff;
      background: #000cf6;
    }
    
    .layer2{
      background: rgba(255, 0, 0, 0.4);
    }
    Lorem ipsum...
    Test test
    More lorem ipsum...
    ...same HTML as above. This one should never overlap the .container_row above.

提交回复
热议问题