一次在商城項目中學到,產品說所有的商品縮略圖都要展示正方形
上代碼
眾所周知,一個元素要為正方形,
height = width
就可以了。可是,如果高度是不限定的呢?如何自適應的保持正方形呢?
<style>
/* 這一段不必要 */
html,body {
height: 100%;
}
/* 以下是關鍵代碼 */
#wrap {
width: 50%;
height: 100%;
background: #089e8a;
}
#box {
width: 100%;
height: 0;
padding-bottom: 100%;
position: relative;
background: #74b1f4;
}
#box img {
position: absolute;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="wrap">
<div id="box"></div>
</div>
</body>
效果:
原理:
這是一個css小技巧:
當 padding-bottom/padding-top/margin-top/margin-bottom 的值為百分比的時候:
計算結果是參照父元素的寬度。
- 當我們設置
height:0;padding-bottom:100%;
- 元素的寬高就始終保持一致了。
width = height
-> 正方形。
complete.