html - float 元素周围的边距?

标签 html css

我正在使用一个页面布局,它有一个侧边栏/标注框,它漂浮在一大块文本内容的一侧,文本内容可能有一些带有不同背景颜色的通知横幅。

这是问题所在(完整的 JSFiddle here ):

不受欢迎的:

Undesired behavior

正如模型中的文本所说,请注意粉红色的“通知”横幅与黄色侧边栏重叠(margin 仅将文本向后踢,而不是与其重叠的 block 元素的边缘)。我希望它看起来更像:

Desired behavior 粉红色背景停在侧边栏的边缘。我能够在模型中通过设置通知横幅的宽度来完成此操作(因为我知道它会与侧边栏相交),但如果该通知出现在页面下方,它就不会扩展到整个宽度。

是否有某种结构/样式可以让我实现这种外观,并且可以灵活地确定通知横幅在内容中的显示位置?

最佳答案

您可以简单地将 overflow: auto 添加到您对 stop its background from leaking behind the sidebar 的通知中,同时保留边栏上的边距。

之所以可行,是因为 overflow 不是 visible,它会在创建新的 block 格式化上下文时干扰 float 。通常,这会导致框根本不与 float (及其边距,如果有的话)相交。请记住,因此,如果通知框的任何部分以其他方式与 float 相交,这将导致整个通知框及其内容被限制在较窄的宽度内。您可以通过在周围的段落和通知框本身中添加/移动文本来看到这一点(我无法使用 fiddle 链接轻松演示这一点)。

规范在 section 9.4 中是这样说的:

In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch). This is true even in the presence of floats (although a box's line boxes may shrink due to the floats), unless the box establishes a new block formatting context (in which case the box itself may become narrower due to the floats).

指向section 9.5 :

The border box of a table, a block-level replaced element, or an element in the normal flow that establishes a new block formatting context (such as an element with 'overflow' other than 'visible') must not overlap the margin box of any floats in the same block formatting context as the element itself. If necessary, implementations should clear the said element by placing it below any preceding floats, but may place it adjacent to such floats if there is sufficient space. They may even make the border box of said element narrower than defined by section 10.3.3. CSS2 does not define when a UA may put said element next to the float or by how much said element may become narrower.

虽然第二个引用在最后听起来令人生畏,但您在此处看到的行为非常一致,而不是您开始看到实现偏差的边缘情况。

关于html - float 元素周围的边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18468923/

相关文章:

PHP 回显表

html - 为什么元素不显示内联?

css - 如何将所有元素 float 到左侧并清除右侧以同时显示下面的几个元素?

html - 同时左右放置一个div

html - 内部左浮动 div 不会垂直扩展容器 div

css - 为什么 `border-left` 会影响 CSS 中椭圆的形状?

javascript - 如何在只读输入字段上设置自定义有效性

html - 无法在 Selenium 中查看整页源代码

javascript - 使该输入文本字段保持焦点并且在我单击其他内容时不会丢失(始终将焦点放在 ID 为 ="input_message"的输入上)?

iOS 应用程序 : webView or PhoneGap?