The cure of aspect ratio design

Paul Li
4 min readFeb 1, 2021

--

Uomo vitruviano

Introduction

Web page layout design 上,如何讓 element 在不同 resolution 上可以維持固定的比例,避免 <img />、<video />、<iframe />…等 element 因為 viewport 變化造成瀏覽閱讀上的不舒適一直都是 web developers 想要解決的要點之一。

此外,Web Vitals > CLS 亦有明確的規範,要在 CLS 這個項目上有所斬獲,事前明確定義 element 寬 / 高 已是刻不容緩的問題,想要維持一定比例加上有效定義出 element 所佔面積,便是 aspect-ratio design 上的重要課題。

CSS > aspect-ratio

aspect-ratio 是 CSS 上一個全新的屬性,透過這個屬性的渲染,便可以明確的定義出該 element 的寬高比例,也就是即使 element width 設置為相對單位 (ex: 100% / 80vw),element 的高度便會立即做出相對應的處理,有了這個屬性的支援,便不再需要其他外力的介入,好比 JavaScript 後天的介入… etc。

在使用上其實方便非常︰

<style>
.aspect-ratio {
aspect-ratio: 1 / 1;
}
</style>
<div class="aspect-ratio">
<!-- this element width : height = 1 : 1 -->
...
...
</div>

如上所示,她的設置方法為 width / height,如果今天我們想要維持 16 : 9 的比例,只要設置為 16 / 9 的 value 即可。是不是相當簡單呢?!

除此之外,一些特定的 element 其實 default 亦會支援 aspect-ratio,可以透過 inspect element 來觀察其變化

img,
input[type="image"],
video,
embed,
iframe,
marquee,
object,
table {
aspect-ratio: attr(width) / attr(height);
}

也就是說,這些特定的 element 透過 attribute > width & height 設置後,便會立即 adopt aspect-ratio 上去,真可謂是貼心非常。

Fallback

看完上面描述後,相信大家都躍躍欲試吧?不過很可惜的,這個新穎的 CSS 屬性目前僅有 Chrome Ver.88 才有支援。興奮之餘難免令人感到失落。

不過其實我們亦可以透過一些 hack 的手法來達成相同的呈現,以下將介紹透過 padding-top 的手法來有效撐開 element 高度,達到於 aspect-ratio 相同的呈現效果。

<style>
.aspect-ratio {
position: relative;
width: 100%;
--w: 4;
--h: 3;
}
.aspect-ratio:before {
content: '';
width: 100%;
padding-top: calc(var(--h) * 100% / var(--w));
display: block;
}
.aspect-ratio .content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
#mei {
--w: 16;
--h: 9;
}
</style>
<div id="mei" class="aspect-ratio">
<div class="content">
<!-- put you content here (this element width : height = 16 : 9) -->
...
...
...
</div>
</div>

透過 CSS Variables 的設置,只要將 — w 以及 — h 設置成所需要的寬高比例,便會透過 calc 立即算出相對應的高度出來,雖然 html 結構上會多一層包覆,不過在 aspect-ratio 尚未普及之前,不失為一個維持比例呈現上的良好作法。

以上,便是個人對於 CSS > aspect-ratio 的一些淺見與心得,提供給同在這條路上奮鬥們朋友們~

Reference

--

--

Paul Li

Paul is the lead programmer of the AMP project at Yahoo Taiwan and is always eager for modern web technologies. He is also focusing on UX for vivid user flow.