8

CSS 外边距合并 Collapsing Margins

 3 years ago
source link: http://misaka.im/index.php/archives/61/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

CSS 外边距合并 Collapsing Margins

2021.01.10默认分类 CSS 0 评

外边距合并 Collapsing Margins

两个块级元素垂直外边距会合并的情况是W3C CSS2 规范定义之初就存在的,并不能说是 bug ,而是 future。

前端开发者往往不了解 CSS属性的由来和设计的本意,在实际使用中产生副作用。

下面几种常见的情况,会出现外边距合并:

相邻元素(包括空内容)之间外边距重叠是经常出现的情况,重叠时一般按照最大值为相邻距离。

迫不得已可以在它们之间加入 <br > 空元素来避免这种情况

嵌套其中一个元素也会有这个问题,但仅仅发生在,嵌套元素没有固定的高度、没有 padding 和 border 的情况。

同样,创建 BFC 块格式化上下文 可以避免两个相邻的块级元素外边距合并的情况发生,但引入 BFC 会破坏原有 HTML 结构,并产生一些复杂的问题。

开发者应该避免这种情况发生,在整体布局上少用外边距。

Everything You Need To Know About CSS Margins

What You Should Know About Collapsing Margins

W3C - 8.3.1 Collapsing margins

重翻译:css2.1规范 8.3.1节(margin边距折叠)

The Rules of Margin Collapse

块格式化上下文 - Web 开发者指南 | MDN


visitor.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK