html - 是否可以将元素的高度设为其容器宽度的 100%?

我想让一个元素具有相同的宽度和高度,所以它是一个完美的正方形。然而,宽度不是一个集合 value 而是由视口加上一些空白定义。空白是由一些 grid fr 单位加上一些在 dsired 元素和它的父元素之外的边距和填充定义的。所以我还没有找到一种简单的方法来计算像 --size: 100vw - **whitespace** 这样的东西。如果可能,我想通过仅使用 CSS 来实现这一点。

这是一个工作示例:

* {
  box-sizing: border-box;
}
.example {
    display: flex;
    flex-wrap: wrap;
}
.example > div {
    background-color: teal;
    border: 4px solid blue;
    border-top: 0;
    border-bottom: 0;
}
.taller {
    flex-basis: 40%;
    height: 500px;
}
.shorter {
    flex-basis: 60%;
    height: 250px;
}
.perfectCircle {
    border: 4px solid red;
    --size: 100%;
    width: var(--size);
    height: var(--size);
    border-radius: 50%;

    position: relative;
}
.perfectCircle > p {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
p {
  flex-basis: 100%;
}
<div class="example">
    <p>The width of the teal containers should define the size of the perfect <del>square</del> circle inside</p>
    <div class="taller">
        <div class="perfectCircle">
            <p>
                This should ALWAYS be a perfect <del>square</del> circle and leave whitespace on top or bottom if needed.
            </p>
        </div>
    </div>
    <div class="shorter">
        <div class="perfectCircle">
            <p>
                This should ALWAYS be a perfect <del>square</del> circle and overflow the container if needed.
            </p>
        </div>
    </div>
</div>

回答1

为此有一个 CSS 属性:https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio

aspect-ratio CSS 属性设置框的首选纵横比,将用于计算自动尺寸和其他一些布局功能。

与 Internet Explorer 不兼容

article {
  width: 40%;
  margin: 1em 30%;
  padding: 0;
  background: lime;
}

section {
  width: 80%;
  margin: 10%;
  background: brown;
}

div {
  width: 100%;
  background: black;
  aspect-ratio: 1 / 1;
}
<article>
  <section>
    <div></div>
  </section>
</article>

相似文章

r - 如何去除 R 中的零方差特征?

我必须从这个有530个变量的数据集中删除方差为零的变量。我使用了nearzerovar函数,但它几乎消除了所有变量,只剩下十个变量。str(Dtrain)'data.frame':19937obs.o...

随机推荐

最新文章