今遇到難題:子元素的長寬比為1:1,當父元素高度大於寬度時,子元素鋪滿父元素的寬度,當父元素高度小於寬度時,子元素鋪滿父元素的高度。如何只用css實現?
印象中我能用傳統方法解決,但是好像那個方法只能横向鋪開。
最終由gemini fast解決了這個問題,用到一個我之前沒見過的css屬性container-type:和cqmin。
.parent {
container-type: size; /* 讓父元素成為計算基準 */
width: 300px;
height: 500px;
display: flex;
justify-content: center;
align-items: center;
}
.child {
/* 100cqmin 代表父容器寬與高之中,最小的那一邊的 100% */
width: 100cqmin;
height: 100cqmin;
background-color: #3498db;
}
不過這只限於長寬比為1:1的情況,暫時不知道其它比例應該如何解決。
後來我不斷追問AI在其它比例時的做法,但是AI始終給不出很好的回答。後來我就想到可以結合container-type: size,cqw/cqh,min(),calc()來實現子元素任何比例都能保持寬高比不變,且能在高或寬鋪滿父元素。
下面的1:2、3:2指的是高度和寬度的比值:
1:2
3:2
源碼也一並奉上:
<style>
.parcts {
container-type: size;
height: 240px;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid black;
animation: widthani 7s ease-in-out infinite;
margin-bottom: 12px;
}
@keyframes widthani {
0% { width: 100%; height: 240px; }
24% { height: 180px; }
50% { width: 0%; }
100% { width: 100%; height: 240px; }
}
.child {
display: flex;
justify-content: center;
align-items: center;
font-size: 36px;
background: grey;
}
.child1 {
height: min(100cqh, calc(100cqw * 1 / 2));
width: min(100cqw, calc(100cqh * 2 / 1));
}
.child2 {
height: min(100cqh, calc(100cqw * 3 / 2));
width: min(100cqw, calc(100cqh * 2 / 3));
}
</style>
<div class="parcts">
<div class="child child1">1:2</div>
</div>
<div class="parcts">
<div class="child child2">3:2</div>
</div>
這是個很新的css標準,直到2023年2月各大瀏覽器才全面支援。