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

后端 未结 9 1278
走了就别回头了
走了就别回头了 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:14

    Of course, the problem is all about getting your height back. But how can you do that if you don't know the height ahead of time? Well, if you know what aspect ratio you want to give the container (and keep it responsive), you can get your height back by adding padding to another child of the container, expressed as a percentage.

    You can even add a dummy div to the container and set something like padding-top: 56.25% to give the dummy element a height that is a proportion of the container's width. This will push out the container and give it an aspect ratio, in this case 16:9 (56.25%).

    Padding and margin use the percentage of the width, that's really the trick here.

提交回复
热议问题