保持宽高比例不变
确保具有可变 width 的元素保持比例相等的 height 值。
- 在
::before伪元素上应用padding-top,使元素的height等于其width的百分比。 - 可根据需要调整
height到width的比例。例如,padding-top为100%将创建一个响应式的正方形(1:1 比例)。
<div class="constant-width-to-height-ratio"></div>
.constant-width-to-height-ratio {
background: #9C27B0;
width: 50%;
}
.constant-width-to-height-ratio::before {
content: '';
padding-top: 100%;
float: left;
}
.constant-width-to-height-ratio::after {
content: '';
display: block;
clear: both;
}