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 (看场景, 不一定适用)

 

posted @ 2022-04-19 18:58  兴杰  阅读(99)  评论(0)    收藏  举报