[CSS] 等比例隨螢幕寬度縮放

--

情境

不管螢幕寬度如何縮放,媒體區塊的寬度都是各佔 30%。

如下圖:

作法

在網路上找到一個方法可以實現這個目的:https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_aspect_ratio_43

<div class="container">
<div class="text">
4:3 Aspect ratio
</div>
</div>
<style>
.container {
position: relative;
width: 100%;
padding-top: 75%; /* 4:3 Aspect Ratio */
}


.text {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
</style>

在外層透過 padding-top 創造高度相對於寬度的比例 75%,再在內層用 top, left, bottom, right 設零撐開。

內層設定觀察

先看沒用 top, left, bottom, right 設零撐開撐開會長怎樣。

.text {
position: absolute;
}

top: 0;看看。

.text {
position: absolute;
top: 0;
}

加了 top: 0;上面有對齊了,但下面還沒對齊。

試試只有 bottom: 0; 看畫面是怎樣。

.text {
position: absolute;
bottom: 0;
}

只有 bottom: 0; 的話會是只有下面對齊,上面沒有。

所以要把上下左右都給 0 ,讓四邊貼齊。

--

--

No responses yet