我已经将一个元素向右浮动,并且出于某种原因它在顶部有一个边距。我不知道它来自哪里。
HTML:
<p>...</p>
<p class="foo">...</p>
<p>...</p>
<p>...</p>
CSS:
p.foo {
width: 500px;
float: right;
}
图片:
codepen.io:http://codepen.io/vbelenky/pen/oEmHt
最佳答案
所有段落都有默认边距:p { margin: 1em 0; }
和一个 float 的没有什么不同。
- 如果您在浏览器中测量 2 个段落之间的边距,您会发现它不是 2em(1em+1em),而是总共 1em。
- 这个 float 段落与其他段落不同,但具有相同的默认边距。
为什么 1.? (垂直)边距被折叠( CSS2.1 Collapsing margins )。这在显示文本时是很自然的(HTML/CSS 主要是关于文本的),在处理其他类型的内容时不是很自然,但浏览器无法知道这种事情......
In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.
(...)
Horizontal margins never collapse.
为什么是 2.?不同之处在于 float 元素的垂直边距不会折叠(与上面相同的链接,请参见绿色的第二个注释)
Margins between a floated box and any other box do not collapse
那么解决方案就很明显了:当涉及到垂直边距时,您必须以不同于那些仍在文档的正常流中的方式来处理 float 元素(至少您必须考虑是否必须修改值或不是)。这里 .foo { margin-top: 0 }
或 .foo { margin: 0 }
(取决于你想要在这个 float 段落底部的边距)
关于html - float 元素有上边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20020001/