style =“ clear:both”的用途是什么?


98

我碰巧看到一个div有风格的clear:bothclearin有style什么用?

<div style="clear:both">

Answers:


249

clear:both 使元素下降到文档中位于其之前的所有浮动元素之下。

您也可以使用clear:leftclear:right使其仅位于那些左右浮动的元素下方。

+------------+ +--------------------+
|            | |                    |
| float:left | |   without clear    |
|            | |                    |
|            | +--------------------+
|            | +--------------------+
|            | |                    |
|            | |  with clear:right  |
|            | |  (no effect here,  |
|            | |   as there is no   |
|            | |   float:right      |
|            | |   element)         |
|            | |                    |
|            | +--------------------+
|            |
+------------+
+---------------------+
|                     |
|   with clear:left   |
|    or clear:both    |
|                     |
+---------------------+

2
另外,它会使父div适应高度。
奥列格(Oleg)2012年

@Jason,您引用的错误仅适用于Windows XP上的Internet Explorer 6。这是一件好事,这些天我们大多数时候不需要支持它。
Yevgeniy Afanasyev

5
@YevgeniyAfanasyev,是的,这是真的。我的评论来自2009年,当时仍然适用。
杰森

20

只需添加到RichieHindle的回答,请Floatutorial,这将引导您完成CSS浮动和清算是如何工作的。


1
2016年2月15日,我无法连接到Floatutorial的服务器(端口80上的连接被拒绝)。
dlu

3

当您使用不带宽度的float时,该行中会保留一些空间。要阻止此空间,可以clear:both;在下一个元素中使用。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.