css实现响应式正方形或固定宽高比


代码如下
HTML:

<div class="square">
  <div class="content">
    Hello!
  </div>
</div>

css:

.square {
  position: relative;
  width: 50%;
  border: 4px solid red;
}
.square:after {
  content: "";
  display: block;
  padding-bottom: 100%;
}
.content {
  position: absolute;
  width: 100%;
  height: 100%;
}

See the Pen jxXeEB by Qing Sheng (@shengoo) on CodePen.

原理如下

.square中创建一个伪元素,使用padding-bottom: 100%;,伪元素会用父级节点的宽度来计算100%,所以高度就是父级的宽度,这样就能实现正方形来。
同理,需要固定宽高比的情况下,都可以使用这种方式。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注