[原創] Something about float and clear in CSS Back

Description

As we all know that, a div element is a block element, which will occupy the whole line.

See the Pen vKrgbZ by aleen42 (@aleen42) on CodePen.

Float

Normally, We'll suppose that all those div elements have been in a normal standard flow (標準流).

CSS have provided an attribute named float to allow you to design block elements into a same line. If you set float to a div, you will find that this element will get rid of the original standard flow, and as following example, you will see that div2 has get rid of the standard flow, and div3 has been moved uppper following behind div1.

See the Pen wWkJwQ by aleen42 (@aleen42) on CodePen.

float attribute can be set as left or right, that means you can float this element to the left or right. For example, if we set float: right; to div3, you will find that this element has been moved to the right side.

See the Pen oLOkxG by aleen42 (@aleen42) on CodePen.

Assume that if we set float: right; to both div2 and div3, see what happens now? We will found that the order of those elements are from right to left, while left to write for both setting with float: left;.

See the Pen jARBAg by aleen42 (@aleen42) on CodePen.

Clear

clear attribute means that a element can clear floated elements in the left or right, or both.

Before adding clear, we can see that a div4has div3 floated in the left side, and div2 floated in the right.

See the Pen KrYmwN by aleen42 (@aleen42) on CodePen.

If we set clear: right; to div4, you'll find that div4 will follow behind div2.

See the Pen AXzRvb by aleen42 (@aleen42) on CodePen.

Self-clear

When we have set float elements in a container, the container will not automatically responsive to these elements. To make the container self-clear, even in an older version of browser, we may have to clear fix for them:

.clearfix:after {
    display: block;
    content: " ";
    clear: both;
    /** try to hide this additional element */
    visibility: hidden;
    height: 0;
    font-size: 0;
}

* html .clearfix {
    /** IE7 */
    zoom: 1;
}

*:first-child + html .clearfix {
    /** IE6 */
    zoom: 1;
}

Summary

For front-end developer, the difficulty of layout is to put different types of elements into one line. Both float and clear have provided you a way to handle it.

results matching ""

    No results matching ""