发布于 3年前

CSS 布局 如何让元素等宽高比

给定可变宽度的元素,它将确保其高度以响应的方式保持成比例(即,其宽度与高度的比率保持恒定)。

HTML

<div class="constant-width-to-height-ratio"></div>

CSS

.constant-width-to-height-ratio {
  background: #333;
  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;
}

说明

padding-top 在...上::before 伪元素使元素的高度等于其宽度的百分比。100% 因此表示元素的高度始终为100% 的宽度,创建一个响应正方形。

此方法还允许内容正常放置在元素内部。

©2020 edoou.com   京ICP备16001874号-3