What does the CSS rule "clear: both" do?

What does the following CSS rule do:

.clear { clear: both; }

And why do we need to use it?


I won't be explaining how the floats work here (in detail), as this question generally focuses on Why use clear: both; OR what does clear: both; exactly do...

I'll keep this answer simple, and to the point, and will explain to you graphically why clear: both; is required or what it does...

Generally designers float the elements, left or to the right, which creates an empty space on the other side which allows other elements to take up the remaining space.

Why do they float elements?

Elements are floated when the designer needs 2 block level elements side by side. For example say we want to design a basic website which has a layout like below...

在这里输入图像描述

Live Example of the demo image.

Code For Demo

/*  CSS:  */

* { /* Not related to floats / clear both, used it for demo purpose only */
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}

header, footer {
    border: 5px solid #000;
    height: 100px;
}

aside {
    float: left;
    width: 30%;
    border: 5px solid #000;
    height: 300px;
}

section {
    float: left;
    width: 70%;
    border: 5px solid #000;
    height: 300px;
}

.clear {
    clear: both;
}
<!-- HTML -->
<header>
    Header
</header>
<aside>
    Aside (Floated Left)
</aside>
<section>
    Content (Floated Left, Can Be Floated To Right As Well)
</section>
<!-- Clearing Floating Elements-->
<div class="clear"></div>
<footer>
    Footer
</footer>

The clear property indicates that the left, right or both sides of an element can not be adjacent to earlier floated elements within the same block formatting context. Cleared elements are pushed below the corresponding floated elements. Examples:

clear: none; Element remains adjacent to floated elements

body {
  font-family: monospace;
  background: #EEE;
}
.float-left {
  float: left;
  width: 60px;
  height: 60px;
  background: #CEF;
}
.float-right {
  float: right;
  width: 60px;
  height: 60px;
  background: #CEF;
}
.clear-none {
  clear: none;
  background: #FFF;
}
<div class="float-left">float: left;</div>
<div class="float-right">float: right;</div>
<div class="clear-none">clear: none;</div>

CSS float and clear

Sample Fiddle

Just try to remove clear:both property from the div with class sample and see how it follows floating divs .

链接地址: http://www.djcxy.com/p/87618.html

上一篇: clearfix类在css中做什么?

下一篇: CSS规则“明确:都是”做什么?