CSS floats, things you don't know

Source: Internet
Author: User

Original link: http://www.cnblogs.com/zhujl/archive/2012/05/08/2489440.html

What did the float do?

How does floating affect the box model of an element?

What is the difference between a floating element and an inline element?

What are the rules for adjusting the position of floating elements?

How does the Clear property work, and what is its purpose?


Floating can even trip an experienced developer, understanding the float will help you solve a lot of CSS problems. Even if you think you know all about floating knowledge, our deep enough analysis may also help you learn something new.


What is floating?

Some elements in the CSS are block-level elements that indicate that they will automatically start another line.

For example, if you create two paragraphs, each paragraph has only one word. These two words will not be together, but will occupy one line.


Other elements are inline elements that indicate that they are on the same line as the previous content.

For example,,<a> can appear in another element, such as <P>, which does not produce extra spaces or break lines.


One way to cheat this layout model is to use floating, which allows one element to move to one side of its line, allowing other content to flow downward along the edge of the element.


A typical example is when you want a picture and a paragraph to appear next to each other, rather than a top-down arrangement. Let's start by creating HTML:

<p>lorem ipsum...</p>


This piece of code alone does not achieve the effect we want. <p> is a block-level element that will have a single line, so the picture and paragraph are shown on a single page.


This behavior can be changed by letting the picture float to the right, as follows:

img {    float:right;    margin:20px;}


The picture then goes to the right, and the paragraph flows down the left side of the picture.


Now something interesting has happened, and when the picture floats, the rest of the content will try to surround it as much as possible. If we resize the container or the browser window and make it narrower, the text will Reflow (reflow) so that it never touches the picture.


How the Box model works

Perhaps you have a deep understanding of the above-mentioned knowledge. However, in order to fully grasp the float, you need to understand more deeply how the two elements interact with one another. For example, what happens if we add a margin between a paragraph and a picture?

p {margin:20px;}


However, this does not create extra space between the picture and the paragraph . In fact, we need to add margin to the picture:

img {margin:20px;}

Maybe you'll ask why? Why does adding <p> margin not increase the spacing between pictures and paragraphs?

The reason is that we don't understand the <p> box model.

  
If you have some doubts about the layout now, try adding one or two border to see what happens. below to <p> add border:

p {    border:solid 1px black;}


As you can see, the picture is actually inside the <p> box model! This can explain the margin problem just now. The margin we add to <p> actually works on the right side of the picture, which is why it can't increase the distance between the picture and the paragraph!


If we want to change this behavior so that the paragraph does not surround the picture, we should let the paragraph float to the left and set a width (if the width of the,<p> is not set by default is 100%, so it is not next to the picture, because if the paragraph is very long, it will go to the next line).

img {    float:right;    margin:20px;} p {    float:left;    width:220px;    margin:20px;}


Crazy floating Rules

Now you know what floats are and how floats affect the box model of related elements. Maybe a lot of people don't know how to adjust the position of floating elements .


Many people in web development will use floating for <li>. Let's look at an example:

<ul>    <li></li>    <li> </li>    <li></li>    <li></li>    <li></li>    <li></li>    <li></li></ul>


All <li> defaults should be arranged vertically, which means that <li> is a block-level element. Even though the picture is an inline element, it is managed by its parent block-level element. To solve this problem, we let <li> float to the left. When multiple <li> in a row are floated, they produce a flow layout similar to the inline elements. However, as you will see, they have some key differences.

Li {    float:left;    margin:4px;}


Now, if all the pictures are of the same height, the following effect will occur.


However, our picture height is not the same, some are 100px, others are 150px. This raises a number of serious problems!


When I first saw the effect, I had a sore egg. Why did picture 4 run to the right? Isn't it supposed to float to the left as far as possible? If we give up floating and use display:inline, the result will be very different.

Li {    display:inline;}


In this example, the image defaults to vertical bottom (bottom) alignment. This is different from our previous example, in order to solve the alignment problem, we add a line of CSS.

img {    vertical-align:top;}


As a result, using display:inline can make it easier to guess the <li> arrangement results. When there is no extra space in the horizontal direction, the next element will start another row.


Why can't floats do this?


The CSS specification outlines 9 rules for floating behavior. But the problem is that only the authors of the norm and those who are bored can understand the rules. Here is an excerpt of one of the rules:

"If The current box is left-floating, and there be any left-floating boxes generated by elements earlier in the source do Cument such earlier box, either the left outer edge of the current box must is to the right of the right OU Ter Edge of the earlier box, or its top must is lower than the bottom of the earlier box. Analogous rules hold for right-floating boxes. "


For these rules, perhaps you understand deeper than I do, but honestly, these rules make me very sore. To simplify it, Josh Johnson gives his 9 rules (note: I think this guy's 9 rules are still very verbose, and I'll streamline it):

1. Floating element's active area

is limited to its parent container element and does not exceed the parent container

2. Position of the floating element

Horizontal: Left or right as far as possible, if there is a floating element in front of it, it will follow it, and if it goes beyond the line, it will be wrapped.

Vertical direction: Top as possible

There are a few things to keep in mind about the position in the horizontal direction:

1) elements that float to the left do not appear to the right of the element that floats to the right

There are a few things to keep in mind about the vertical position:

1) Floating elements are no higher than the top of the container

2) floating elements will not be higher than the previous block level element or floating element

3) Floating elements will not be higher than the previous inline element

Vertically-oriented rules have higher precedence than horizontal in layout


In general, floating elements move to the left or right. Unless there is a floating element in front of the element, it is immediately next to the element that precedes it.


What's really confusing is that floating elements are as top-ranked as possible, and that vertical positioning rules are more priority than horizontal floating rules.


In the previous example, the image 2 is taller than the height of the row, so after the picture 3 is finished, there is still enough vertical space to place the image 4.


Remember, when you have a floating element (not in the tail row), the floating element behind it must occupy a vertical space greater than or equal to it to trigger a line break .


Floating order

For example, we have a list of 6 images.

<ul>    <li></li>    <li> </li>    <li></li>    <li></li>    <li></li>    <li></li></ul>


If we float the picture to the left, they will be arranged in the original order. But what if it floats to the right?


It can be found that the first picture occupies the right position. Similarly, the fourth picture also occupies the right position after a line break. That's why you rarely see the list items in the navigation bar floating to the right.


Clear floating

Floating makes it easy to implement some layouts, such as creating N-column content. However, once a float is used, it will affect the normal flow layout of the document. For example, in that example, we wanted to add a paragraph below the list.


The result may not be what you want. The workaround here is to use the clear property, which is to clear the float on one side of the element. For example, we use Clear:left for a second list item

UL Li:nth-child (2) {    clear:left;}

This code tells the browser that the top of the second item must be lower than the bottom of the floating element in front of it . If all list items are floating to the right, you need to use the Clear:right


Add paragraph text to see again


Obviously this is still not the effect we want, the workaround is to use clear for the paragraph, which causes the paragraphs to appear below the floating elements instead of adjacent to them.

p {    Clear:both;}


In fact, we just need to clear the left side of the float, but when a developer to make sure that all floats are cleared, Clear:both is a very common method.

Floating Problems and Clearfix

When an element contains only floating elements, the container element is highly overlapping (as with a height of 0, that is, the top and bottom edges of the height overlap). To illustrate this, let's use just the example to add a background color to the list.

UL {    Background:gray;}

  

If the list item does not float, you can see that the entire list is gray, and the list items are arranged from top to bottom.


Now that we float all the list items, <ul> only contains floating elements, so it's highly overlapping, and novices will be curious about where the background color is.


There are several ways to solve this problem, the simplest of which is to set the height of the container element directly.

UL {    height:300px;}

So the background color came back again. However, this approach often does not satisfy us, because this method is completely ineffective when we need the height and content adaptation of the container. If we add three more list items, this is not enough.


Summon Clearfix

Now it's the turn to Clearfix, which solves the problem of high overlap through the clear attribute.


We often create an empty element (usually a div) that is the same as the floating element, and then set the class to "Clearfix". Back to CSS, we add this line style:

. clearfix {    clear:both;}


This solves the problem of height.

The principle: we know that when an element contains only floating elements, the height overlaps (the effect and the height is 0), when the element has a child element, even if it is an empty element, but it does not float, but also clears all floats, so this empty element will appear below all elements, Thus propped up the height of the container, so height:auto back to normal.


The disadvantage of this approach is that there is an extra element in HTML that does not conform to the idea of semantics.


The new workaround is to use the overflow property, and if you set the value to hidden or auto, you can also resolve the problem of high overlap.

UL {    Overflow:auto;}

This method is simpler and more elegant, but there is one more question to ask, if the container element must be set to overflow:visible, what should you do?


The method is first used: Before and: After creating something in the element that does not float, but in fact you do not want to appear any superfluous things, so we set an empty string, but to set the display:table, thus creating an anonymous cell (is not remembered <td></td>? ), and finally use the old-fashioned, clear float.


In order to be compatible with the old version of IE, use its unique zoom:1 to clear the float.

/* For modern browsers */.cf:before,.cf:after {    content: "";    display:table;} . cf:after {    clear:both;}/* for IE 6/7 (trigger Haslayout) */.cf {    zoom:1;}

  

  

http://designshack.net/articles/css/everything-you-never-knew-about-css-floats/

(turn) CSS floats, things you don't know

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.