CSS清除如何工作? [英] How does CSS clearing really work?

查看:83
本文介绍了CSS清除如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个< div> ,我想要在一条线上。根据 W3Schools ,此规则:

  div.foo {
clear:both;
}

...应该意味着:


左侧或右侧不允许有浮动元素。


但是,如果我将两个< div> 元素浮动,并将上述规则应用于第一个,第二个不会倾斜。



另一方面,如果我应用clear:left到第二个< div& code>,它向下移动到下一行。这是我的正常方法,但我不明白为什么我必须这样做。



W3Schools的描述是上面描述不好,还是我错过了什么? 清除规则是否只能移动其应用的元素?



回答



感谢Michael S和John D的良好解释。 Warren指出 CSS2规范,这就是我找到这个答案(强调我的) :


此属性表示元素框的哪些边可能不与较早浮动


因此: clear 只影响元素的位置



令人失望的是我无法告诉我的< div> 使其他div向下移动,但他们是休息。 :)

解决方案

当对一个元素应用clear时,它将移动THAT元素,权利。它不会重新定位任何其他元素,它只是将元素移动到一个位置,周围没有什么。



编辑 / p>

清除项目上方的项目未移动,元素下方的项目可移动。另请注意评论


中的其他评论

I have a <div> that I want to be on a line by itself. According to W3Schools, this rule:

div.foo {
clear: both;
}

...should mean this:

"No floating elements allowed on either the left or the right side."

However, if I float two <div> elements left, and apply the rule above to the first one, the second one does not budge.

On the other hand, if I apply "clear: left" to the second <div>, it moves down to the next line. This is my normal approach, but I don't understand why I have to do it like this.

Is the W3Schools description above poorly stated, or am I missing something? Is a clearing rule only able to move the element to which it is applied?

Answer

Thanks Michael S and John D for the good explanations. Warren pointed to the CSS2 spec, and that's where I found this answer (emphasis mine):

This property indicates which sides of an element's box(es) may not be adjacent to an earlier floating box.

So: clear only affects the position of the element to which it is applied, relative to elements that appear before it the code.

Disappointing that I can't tell my <div> to make other divs move down, but them's the breaks. :)

解决方案

When you apply clear to an element, it will move THAT element so that it doesn't have items left or right of it. It does not re-position any of the other elements, it simply moves the element to a position where nothing is around it.

Edit

Items above the item cleared are not moved, items below the element COULD be moved. Also note the additional comment in the comments

这篇关于CSS清除如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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