方法1
在保持元素寬高比恆定的情況下,要使得元素可以和父元素同比縮放。此時會用到 padding。
需要知道的是:一個元素的 padding,如果值是一個百分比,那這個百分比是相對於其父元素的寬度而言的,padding-bottom 也是如此。
使用 padding-bottom 來代替 height 來實現高度與寬度成比例的效果,將 padding-bottom 設置爲想要實現的 height 的值。同時將其 height 設置爲 0 以使元素的“高度”等於 padding-bottom 的值,從而實現需要的效果。
此時CSS代碼如下:
div {
padding-bottom: 20%;
height: 0;
}
方法2
用vh單位
html
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="ui-square-nerd"></div>
<div class="ui-square"></div>
</body>
</html>
css
.ui-square-nerd {
width: 20%;
height: 0;
padding-bottom: 20%;
background: blue;
}
.ui-square {
margin-top: 30px;
width: 20vh;
height: 20vh;
background: green;
}