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 @   兴杰  阅读(80)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示