2018-11-19 15:02:54

在响应式开发中,有一些元素需要按等比例进行显示,比如说一个上传图片的区域,我们需要严格限制上传区域的比例为3:1,上传完成后的预览图宽高均为100%,才能保证用户上传后看到上传的图片是否合乎比例,是否在实际应用时会产生变形或裁剪的问题。那么此时就需要在适应不同宽度的屏幕中进行等比例缩放div区域。

方案一:通过媒体查询,设定在不同屏幕宽度下div的高度和宽度,如下示例

@media only screen and (min-width: 100px) and (max-width: 640px) {

div{

width: 300px;

height: 100px;

}

}@media only screen and (min-width: 641px) and (max-width: 789px) {

div{

width: 600px;

height: 200px;

}

}

方案二:通过设置padding为百分比,高度为0,然后高度自然溢出。

div{

width:calc(100% - 100px);

height:0;

padding-bottom:calc((100% - 100px)/3;

}

如此得到的div宽高比为3:1。这个方法依赖于一个基础却又容易混淆的css知识点:当margin/padding取形式为百分比的值时,无论是left/right,还是top/bottom,都是以父元素的width为参照物的,下面是W3C的规范原文:

Note that in a horizontal flow, percentages on ‘margin-top’ and ‘margin-bottom’ are relative to the width of the containing block, not the height (and in vertical flow, ‘margin-left’ and ‘margin-right’ are relative to the height, not the width).

Note that percentages on ‘padding-top’ and ‘padding-bottom’ are relative to the width of the containing block, not the height (at least in a horizontal flow; in a vertical flow they are relative to the height).

更多推荐

html如何设置div宽高比,使用css设置div等比例缩放高宽