可以使用 CSS 中的 padding 或者 transform 来实现。

使用 padding:

首先需要设置长方形元素的宽度和高度,然后通过 padding 来撑开元素,使其形成一个正方形。具体代码如下:

<div class='rectangle'>
  <div class='square'></div>
</div>
.rectangle {
  position: relative;
  width: 200px;
  height: 400px;
  background-color: #f5f5f5;
}

.square {
  position: absolute;
  top: 40px;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  width: 0;
  height: 0;
  border-top: 60px solid transparent;
  border-bottom: 60px solid transparent;
  border-left: 60px solid #333;
}

其中,长方形元素的宽度为 200px,高度为 400px。正方形元素使用绝对定位,并设置距离长方形元素顶部 40px 的位置。通过设置上、下、左、右的值为 0,并设置 margin 为 auto 来使正方形居中。然后通过设置 border 来撑开元素,border-top 和 border-bottom 的值为 60px,border-left 的值为 60px,这样就形成了一个边长为 60px 的正方形。

使用 transform:

可以使用 CSS 中的 transform 来对正方形进行缩放。具体代码如下:

<div class='rectangle'>
  <div class='square'></div>
</div>
.rectangle {
  position: relative;
  width: 200px;
  height: 400px;
  background-color: #f5f5f5;
}

.square {
  position: absolute;
  top: 40px;
  left: 0;
  right: 0;
  margin: auto;
  width: 60px;
  height: 60px;
  background-color: #333;
  transform: scale(1, 1);
}

其中,长方形元素的宽度为 200px,高度为 400px。正方形元素使用绝对定位,并设置距离长方形元素顶部 40px 的位置。通过设置上、下、左、右的值为 0,并设置 margin 为 auto 来使正方形居中。然后设置正方形元素的宽度和高度为 60px,并设置背景颜色为 #333。最后通过 transform 来对正方形进行缩放,scale 函数的第一个参数表示水平方向的缩放比例,第二个参数表示垂直方向的缩放比例,这里都设置为 1,表示不进行缩放。

JS 在长方形元素内绘制等比例正方形:Padding 和 Transform 方法

原文地址: https://www.cveoy.top/t/topic/orTt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录