为什么< div class =" clear">< / div>是用在多个浮动DIVS之后在容器DIV中? [英] Why <div class="clear"></div> is used after multiple floating DIVS in a container DIV?
问题描述
我在许多地方遇到过< div class =clear>< / div>
,但我不知道为什么会这样做?有人可以告诉我这个,为什么它在css中使用?这是CSS:
I have encountered a <div class="clear"></div>
at many places, but I am not aware why is it done? Can someone brief me on this, why it is used in css? This is the CSS:
div.clear {
clear:both;
}
推荐答案
元素的高度由其子元素确定(除非明确设置)。例如:
The height of an element is determined by its child elements (unless it is explicitly set). E.g.:
+------A------+
|+-----------+|
|| B ||
|+-----------+|
|+-----------+|
|| C ||
|+-----------+|
+-------------+
of A取决于它的孩子C的下边界的位置。
The height of A is determined by where the lower border of its child C is.
现在,浮动元素不计入父母的高度,它们被取出常规流程:
Now, floating elements do not count towards the height of their parents, they're taken out of the regular flow:
+------A------+
+--+---------++
| B |
+---------+
+---------+
| C |
+---------+
A元素折叠为
介绍清除元素以恢复正确的高度:
Clearing elements are introduced to restore the correct height:
+------A------+
| +---------+|
| | B ||
| +---------+|
| +---------+|
| | C ||
| +---------+|
|+-----D-----+|
+-------------+
元素是具有 clear
属性集的零高度元素。这会导致它低于浮动元素(它清除它们)。这导致A有一个普通的子元素来计算它的高度。这是最典型的用例。
The D element is a zero-height element with the clear
attribute set. That causes it to fall below the floated elements (it clears them). That causes A to have a regular child element to calculate its height by. That's the most typical use case at least.
引入额外的HTML元素的更好的解决方案是将A设置为 overflow:hidden
虽然。这具有强制高度计算的效果,其具有将高度增长到期望尺寸的相同效果。这个解决方案可能有也可能没有其他副作用。
The often better solution to introducing extra HTML elements is to set A to overflow: hidden
though. That has the effect of forcing a height calculation, which has the same effect of growing the height to the desired size. This solution may or may not have other side effects though.
这篇关于为什么< div class =" clear">< / div>是用在多个浮动DIVS之后在容器DIV中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!