CSS – Width & Height Auto and Percentage
前言
這個非常基礎, 我在學 W3Schools 之前就已經會了, 所以之前一直沒用記入起來. 但偶爾遇到一些場景時還是會被坑到.
所以特別寫這一篇, 提升記憶.
width / height auto & percentage
width / height initail value 都是 auto, 意思是它會依據不同的情況去計算最終的 width 值, 在 Flex 對 width / height: auto 的影響 有提到過.
width
block element auto = fill container = 100% parent
inline element auto = hug content (depend on child)
percentage = depend on parent
height
block / inline element auto = hug content (depend on child)
percentage = depend on parent
迴圈 depend problem
有時是 depend on child 有時是 depend on parent 就有可能迴圈.
比如 parent div height auto, 這個屬於 hug content
但是 child div height 100% 這樣就錯亂了.
所以當使用 percentage 的時候一定要確保 parent 有具體的 value
比如 child 設定 height / max-height: 50% 那麼 parent 的 height 就不可以是 auto, max-height percentage 是 depend on parent height 而不是 max-height 哦
參考: stackoverflow – Percentage Height HTML 5/CSS
這也是最常踩的坑了. 有時候不得不 wrapper 一層的時候要特別小心, 有時也可以把 percentage 換成 100vh 這種方式可以跳過 parent auto (看場景, 不一定適用)