为什么浮动元素的背景似乎独立于内容移动? [英] Why does the background of a floated element appear to move independent of the content?

查看:73
本文介绍了为什么浮动元素的背景似乎独立于内容移动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的CSS代码中,看来 divTwo 的背景已经移到 divOne 之后。但是 divTwo 的内容似乎已被抛在后面-为什么div的背景似乎独立于内容而移动?

In the CSS code below, it appears that the background of divTwo has moved behind divOne. But the content of divTwo appears to have been left behind - why does the background of the div appear to move independently of the content?

#divOne {
  width: 300px;
  height: 100px;
  background-color: yellow;
  margin:5px;
  float:left
}
#divTwo {
  width: 300px;
  height: 100px;
  padding:5px;
  background-color: green;
}

<div id="divOne">Div01</div>
<div id="divTwo">Div02</div>

Chrome的结果

推荐答案

divTwo的内容不是独立移动的。内容是文本,因此呈现在线框中。

The content of divTwo is not moving independently. The content is text, so it's rendered in a line box.

现在,当未浮动且未清除的块忽略它们之前的浮动元素时, ,它们包含的线框则没有。线框将避免浮动元素,并与浮动元素并排,或者在浮动元素下方(如果没有空间的话)放在浮动元素下方。

Now while unfloated, uncleared blocks ignore the presence of floated elements that precede them, the line boxes that they contain don't. The line boxes will avoid the floated element and go either alongside the floated element or, if there's no space for them there, underneath the floated element.

旁边没有空格,因此文本位于float元素的下方。但是,由于您为divTwo设置了固定的高度,因此divTwo下方和内部都没有足够的空间用于线框。因此,文本内容溢出 divTwo,因此文本显示后没有divTwo的背景。

In your example, there is no space alongside, so the text has gone underneath the floated element. But since you've set a fixed height for divTwo, there's not enough space underneath and yet inside divTwo for the line box either. So the text content overflows divTwo, hence the text appears without divTwo's background behind it.

这篇关于为什么浮动元素的背景似乎独立于内容移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆