高级前端
css
【Q531】子元素垂直居中,并且该子元素的长度/宽度为父容器宽度(width)一半的正方形

子元素垂直居中,并且该子元素的长度/宽度为父容器宽度(width)一半的正方形

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 544 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

垂直居中长度为父容器一半的子元素 - Codepen (opens in a new tab)

<div class="container">
  <div class="item"></div>
</div>

以前采用百分比撑高 padding,那这种方案已经过时,会挤压 Content 内容,无法在其中填充内容(需要绝对定位)。

可使用最新的属性 aspect-ratio,即长宽比

.container {
  display: grid;
  place-items: center;
}
 
.item {
  width: 50%;
  aspect-ratio: 1/1;
}