CSS 折叠边距的意义是什么?

CSS2盒子模型告诉我们 相邻垂直边界折叠

我觉得这很烦人,因为它是很多设计错误的源头。我希望,通过理解折叠边界的目的,我将理解何时使用它们,以及在不需要它们时如何避免它们。

这个特性的目的是什么?

8771 次浏览

The general meaning of "margin" isn't to convey "move this over by 10px" but rather, "there must be 10px of empty space beside this element."

I've always found this is easiest to conceptualize with paragraphs.

If you just gave paragraphs margin-top: 10px and had no margins on any other elements, a series of paragraphs would be spaced beautifully. But of course, you'd run into trouble when placing another element underneath a paragraph. The two would touch.

If margins didn't collapse, you'd hesitate to add margin-bottom: 10px to your previous code, because then any pair of paragraphs would get spaced 20px apart, while paragraphs would separate from other elements by only 10px.

So vertical margins collapse. By adding top and bottom margins of 10px you're saying, "I don't care what margin rules any other elements have. I demand at least 10px of padding above and below each of my paragraphs."