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

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

    I had to set

    Container_height = Element1_height = Element2_height

    .Container {
        position: relative;
    }
    
    .ElementOne, .Container ,.ElementTwo{
        width: 283px;
        height: 71px;
    }
    
    .ElementOne {
        position:absolute;
    }
    
    .ElementTwo{
        position:absolute;
    }
    

    Use can use z-index to set which one to be on top.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-22 22:16

    Due to absolute positioning removing the elements from the document flow position: absolute is not the right tool for the job. Depending on the exact layout you want to create you will be successful using negative margins, position:relative or maybe even transform: translate. Show us a sample of what you want to do we can help you better.

    0 讨论(0)
提交回复
热议问题