css 实现元素长宽等比缩放

实现思路(长宽比2:1): 以父级元素为基准, 子级 width:100%; (也就是父级宽度的 100%), padding-top:50% (也就是父级宽度的 50%, 根据 css 规范, padding 用百分比表示的话, padding: 100% 等于父元素的宽度);

为什么不直接 `width: 100%; height: 50%;?
那样高度就成了父级高度的 50% (不合题意, 除非父级宽高相等);

<style type="text/css">
#container {
    width: 80%;
    height: 500px;
}
.attr {
    width: 100%;
    height: 0;
    padding-bottom: 50%;
    background-color: #008b57;
}
</style>

<div id='container'>
    <div class='attr'></div>
</div>

Tips: padding-bottom 的百分比值是相对父元素的宽度来算的

猜你喜欢

转载自www.cnblogs.com/liuyishi/p/9553249.html
今日推荐