Responsive Design: Why does height zero & padding-bottom work for making a div responsively sized?

落爺英雄遲暮 提交于 2020-01-22 12:28:39

问题


After looking through Zurb Foundation's code, I noticed they were using a CSS approach like this to allow a responsive square div:

.div{
    position:relative;
    width:33%;
    height:0;
    padding-bottom:33%;
}
.divInner{
    position:absolute;
    width:100%;
    height:100%;
}

I've been using this approach on some newer projects (still in private dev), but don't know the browser support for it or why the height is even able to mimic the width size. Does anyone know why this happens? Thanks!


回答1:


The second element is positioned absolutely relative to is container. Which is positioned relative.

In CSS, percentage based padding is relative to the width of the element. That is what creates the square effect.

And is also why if you add the same size padding to all sides, all sides have the same percentage of padding. It is relative to one measurement (width) and NOT both width and height. that would cause the padding to be skewed if the the element was not square.



来源:https://stackoverflow.com/questions/15909369/responsive-design-why-does-height-zero-padding-bottom-work-for-making-a-div-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!