html - float 元素有上边距

标签 html css css-float

我已经将一个元素向右浮动,并且出于某种原因它在顶部有一个边距。我不知道它来自哪里。

HTML:

<p>...</p>
<p class="foo">...</p>
<p>...</p>
<p>...</p>

CSS:

p.foo { 
  width: 500px;
  float: right;
}

图片:

The image in which the <p> has a top margin

codepen.io:http://codepen.io/vbelenky/pen/oEmHt

最佳答案

所有段落都有默认边距:p { margin: 1em 0; } 和一个 float 的没有什么不同。

  1. 如果您在浏览器中测量 2 个段落之间的边距,您会发现它不是 2em(1em+1em),而是总共 1em。
  2. 这个 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/

相关文章:

JavaScript 内联 SVG 未渲染

css - 覆盖 index.html css react 元素

html - 并排居中的盒子

html - 正确扩展 HTML 小部件

html - 如何将文本定位到右侧?

javascript - HTML5 表单验证与 javascript 篮子验证相结合?

html - 如何更改 Bootstrap 3 中一行的颜色?

CSS 在窗口调整大小时 float : Behavior breaks design

javascript - 如何为移动用户 (Android/iPhone) 的 "Add to home screen"响应式网站创建链接

javascript - 需要帮助调试 - IE 不在网站上显示 jquery 背景 slider