如何将正方形放入矩形以匹配其高度?

问题描述 投票:0回答:1

假设我们有响应矩形。我需要将方形元素放入矩形中,它应该是其高度的 100%。你怎么能只用 CSS(没有 SVG 和 JS,没有固定尺寸)呢?换句话说:让子元素的宽度等于父元素的高度?

使用 viewbox 属性将 SVG 作为子元素很容易完成,但我需要纯 CSS 解决方案。

<div style="width: 95vw; height: 100%; border: 2px solid #f00">
  <div style="border: 2px solid #0f0">I'm 100% of parent's height but also I'm not square</div>
</div>

css height width equals
1个回答
0
投票

你可以使用 padding-top 属性

<div class="rectangle">
  <div class="square"></div>
</div>

.square {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%; 
  height: 100%; 
  background-color: red;
}

.rectangle {
  position: relative;
  width: 100%;
  height: 0;
  padding-top: 100%; 
}



© www.soinside.com 2019 - 2024. All rights reserved.