這個問題在這里已經有了答案: 通過 CSS 根據高度設定元素寬度 10 個答案 使用 CSS 保持 div 的縱橫比 37 個答案 15 小時前關閉。
我想讓一個元素具有相同的寬度和高度,所以它是一個完美的正方形。然而,寬度不是一個設定值,而是由視口加上一些空白定義。空白是由一些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>
uj5u.com熱心網友回復:
為此有一個 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/477749.html
上一篇:如何防止div在視口上方溢位?
下一篇:標題高度未擴展到子元素的大小
