A couple of years ago, when developers first started moving to tableless HTML markup, the CSS float property suddenly took on a very important role. The reason the float property became so common was because, by default, block elements did not line up next to each other in a column-based format. Since columns are required in virtually every CSS schema, this property has become used to - and even abused.

Property float in CSS, allows the developer to include table-like columns in HTML markup without using tables. If not for the property float, then CSS layouts would not be possible other than using absolute and relative positioning - which would be sloppy and make the layout layout unmaintainable.

In this article we will tell you what is a property float and how it affects elements in specific contexts. We'll also take a look at some of the differences that may arise with this property across the most commonly used browsers. Finally, we'll demonstrate a few practical applications properties float. This should also provide a comprehensive and thorough discussion of this property and its impact on CSS development.

CSS Float Property Definition and Syntax

The purpose of the float property is to push a block element to the left or right, taking it out of the document flow. This allows the current content to naturally collapse around the floating element. This concept is similar to what you see every day in printed literature, where photographs and other graphic elements are aligned to one side and the content (usually text) flows naturally around the element aligned around the left or right edge.

The image above shows the “Readers” section of the .net magazine site with 3 reader photos that are left aligned in their columns with text wrapping around the images. This is the basic idea behind the float property in CSS layouts, and it demonstrates one of the techniques used in tabular design.

The effectiveness of using floats in multi-column layouts was explained by Douglas Bowman in 2004 in his classic presentation No More Tables:

Bowman explained the principles behind tableless layout, using an old Microsoft site as a reference. Floats were prominently used in his false overhaul of Microsoft markup.

Syntax

The Float property can take one of 4 values: left, right, none, and inherit. This is declared as shown in the code below:

#sidebar ( float: left; )

#sidebar (

float: left;

The most commonly used values ​​are left and right. The value none or the initial float value for any HTML page element is the default value. The inherit value, which can be applied to almost every CSS property, does not work in versions Internet Explorer, including 7.

The float property does not require any other property to be applied to the float element, however, in order to function correctly, float will work more efficiently under certain circumstances.

Typically, a floating element should have explicitly set width(unless it's a replaced element , like an image). This ensures that float behaves as expected and helps avoid problems in some browsers.

#sidebar ( float: left; width: 350px; )

#sidebar (

float: left;

width: 350px;

Features of floating elements

The following is a list of the behavior of floating elements, according to the CSS2 specification:

A left-floated block will be floated to the left until its left edge (or edge boundary if there is no edge) touches either the edge of the block's contents or the edge of another floated block

If the size of a floated block exceeds the available horizontal space, then the floated block will be shifted down

Non-positioned, non-floated block elements act like floating elements, i.e. is outside the document flow

The edges of a floated block will not match the edges of adjacent blocks

Root element( ) cannot be floated

An inline element, one that is floated, is converted to a block element

Float in practice

The most common use case for the float property is to float an image with text wrapping it. For example:

Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui.

Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus.

The CSS applied to the image in the box above looks like this:

img ( float: left; margin: 0 15px 5px 0; border: solid 1px #bbb; )

img(

float: left;

margin : 0 15px 5px 0 ;

border : solid 1px #bbb ;

The only property that can achieve this effect is the float property. The other properties (margin and border) are there for aesthetic reasons. Other elements in the block (tags

With text in them) do not need any styles.

As mentioned earlier, floated elements are pushed out of the flow of the document, and other block elements remain in the flow, acting as if the floated element were not even there. This is demonstrated visually below:

This box is floated left

This

Element has a different background color to show that it spans the width of its parent, ignoring the floated element. This inline text, however, wraps around the floated box.

In the above example

block-level element, so it ignores the floated element spanning the width of the container (minus padding). All non-floated, block-type elements will behave similarly.

The text in a paragraph is inline, so it wraps the floated element. The floated block is also given margin options to offset it from the paragraph, making it visually clean so that the paragraph element ignores the floated block.

Cleaning floats

Layout issues with floats are usually resolved by using the clear CSS property, which allows you to “clear” floated elements from the left or right, or both.

Let's look at an example that comes up often - the footer wraps around right side 2-clonal markup:

Left column floated left

If you look at the IE6 and IE7 page, you won't see any problems. The left and right columns are in place, and the footer is at the bottom. But in Firefox, Opera, Safari and Chrome, you will see that the footer moves out of place. This is caused by applying float to the columns. This is correct behavior, although it is more problematic. To solve this problem, we use the above clear property, relative to the footer:

#footer ( clear: both; )

#footer (

clear: both;

The result is shown below:

Left column floated left

Right column also floated left

The clear property will clear only floated elements, so applying clear: both to both columns would not cause the footer to drop down, because the footer is not a floated element.

The clear property will clear only floated elements. The use of clear is this: both columns will not omit the footer because it is not a floated element.

So use clear on non-floated elements, and even sometimes on floated elements, to force page elements to occupy their designated positions.

Fixing Parent Dropout

One of the most common features of float markup is “leave-parent”. This is demonstrated in the example below:

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.

Notice that the base of the floated image appears outside its parent. The parent is not fully expanded to contain a floated image. This is caused by what we discussed earlier: the floated element is outside the natural flow of the document, although all the elements of the block are displayed, but the floated element is not there. This is not a CSS bug, everything is according to the CSS specifications. All browsers do the same in this example. It should be said that, in this example, adding container width can prevent the problem in IE, but it should also solve the problem for Firefox, Opera, Safari, or Chrome.

Solution 1: Float for container

The easiest way to solve this problem is float for parent element:

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.

The container now expands to accommodate all of the child elements. But unfortunately, this fix will only work in a limited number of cases, since the floating parent may have undesirable consequences for your layout.

Solution 2: Add Additional Markup

This is an outdated method, but it is a simple option. Simply add an additional element to the bottom of the container and "clean" it. This is what the HTML code will look like after implementing this method:

XHTML

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.

"//media.smashingmagazine.com/cdn_smash/wp-content/uploads/2009/10/lifesaver.jpg" width = "200" height = "222" alt = "" />

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.

And as a result, the CSS is applied to the new elements:

Clearfix ( clear: both; )

Clearfix (

clear: both;

You can also do this via
tag with the current style. Either way, you will get the desired result: the parent container will expand to include all of its children. But this method is not recommended because it adds non-semantic code to your markup.

Solution 3: The after pseudo-element

The :after pseudo-element adds an element to the rendered HTML page. This method has been used quite widely to solve float-clearing problems. This is what the CSS looks like:

Clearfix:after ( content: "."; display: block; height: 0; clear: both; visibility: hidden; )

Clearfix:after (

content : "." ;

display: block;

height: 0;

clear: both;

visibility: hidden;

The CSS class “clearfix” applies to any container that has float children and does not expand to include them.

But this method does not work for Internet Explorer up to version 7, so for IE you need to use one of the following options:

Clearfix ( display: inline-block; ) .clearfix ( zoom: 1; )

Clearfix (

display: inline-block;

Clearfix (

zoom: 1;

Depending on the type of problem, you are dealing with one of two solutions that will resolve this issue in Internet Explorer. It should be noted that the zoom property is not a standard Microsoft property and therefore your CSS will become invalid.

Since the :after pseudo-element doesn't work in IE6/7, the code is a bit bloated and tricky, and additional styling is required that isn't valid for IE only, so this solution isn't the best way, but it's probably the best we've looked at. still.

Solution 4: Overflow Property

By far the best and easiest way to solve the parent dropout problem is to add overflow: hidden or overflow: auto to the parent element. It's clear, easy to maintain, works in almost all browsers, and doesn't add any unnecessary markup.

Notice that I said "almost" in all browsers. This is because it doesn't work in IE6. But, in many cases, the parent container will have a set width, which fixes the problem in IE6. If the parent container doesn't have a width, you can add an IE6 single style with the following code:

// This fix is ​​for IE6 only .clearfix ( height: 1%; overflow: visible; )

// This fix is ​​for IE6 only

Clearfix (

height: 1%;

overflow: visible;

In IE6, the height property is incorrectly treated as min-height, so this forces the container to include its children. The Overflow property is then set back to “visible” to ensure that the content is not hidden or scrolled over.

The only downside to using the overflow method (in any browser) is the possibility that the element's content will have scroll bars or hide content. If there are any elements with negative margins or absolute positioning in the parent, they will be hidden if they extend beyond the parent, so this method should be used carefully. It should also be noted that if the contained element had a specified height or min-height, then you definitely wouldn't be able to use the overflow method.

So it's not really a simple cross-browser solution this problem. But almost any float cleaning problem can be solved by one of the above methods.

Related float errors in Internet Explorer

Over the years, there have been numerous articles published online discussing common errors associated with floats in CSS markup. All of them, not surprisingly, deal with problems specific to Internet Explorer. Below, you will find a list of links to a number of articles that discuss float-related issues:

Changing the float property using JavaScript

in order to change CSS value in JavaScript, you must access the object's style by converting the intended CSS property in the “Camel case” For example, the CSS property “margin-left” becomes marginLeft, the background-color property becomes BackgroundColor, and so on. But with the float property, things are different because the word float is already reserved in JavaScript. Therefore the following will be incorrect:

Style. styleFloat = "left" ;

// For all other browsers

myDiv. style. cssFloat = "left" ;

Practical Use of Float

Floats can be used to solve a number of problems in CSS markup. Some examples are described here.

2-column, fixed width

3 Columns, Equal Height Layout

Floated image with title.

Similar to what we discussed earlier in Float in Practice, Max Design describes how floating an image with a title allows text to wrap around it naturally.

Horizontal navigation with unordered lists

The float property is a key component in coding sprite-based horizontal navigation bars. Line25's Chris Spooner describes the creation of Menu of Awesomeness, which tags

  • , holding navigation buttons use float: left:

    To demonstrate the importance of the float property in this example, here is a screenshot of the same image after using firebug to remove the float: left:

    Grid-Based photo galleries

    A simple use of the float property is to float:left a series of photos contained in an unordered list, which produces the same result as what you would see in table markup.

    Foremost Canada's product page (see image above) displays its products in a grid format next to a sidebar. Photos are displayed as an unordered list with a float property, for all

  • elements set to float: left. This works better than a table grid because the number of photos in the gallery can change without the layout being affected.

    Paragon Furniture's futons page (see image above) is another example of a product page using an unordered list with floated tags

  • .

    iStockphoto's search results page (see image above) has the same grid of structured photos, here the photos contain float:left

    tags, not
  • tags.

    Alignment fields with a button

    Default form element modeling for different browsers may be problematic. Often in one form field, such as a search form, you need to put element next to the “send” button.

    Formatting cascading tables). This language has existed since 1996 and is still evolving. On this moment developers are already using the third version of CSS. Using the CSS programming language, it is possible to create a completely beautiful and pleasant website that will not seem outdated or inconvenient for the user, even if you do not use JavaScript at all. The modern capabilities of the third version allow you to do this.

    Developers can also use more convenient formatting options, such as Flexbox or Position to change the location of an element on the site, but first things first. First, you should understand the advantages and disadvantages of the Float property.

    CSS Float - why is it needed?

    Float is a property for positioning elements. Every day it can be seen on the pages of newspapers and magazines, looking at the pictures and text that very neatly flows around them. In the world of HTML and CSS code, the same thing should happen when using the Float function. But it is worth remembering that image editing is not always the main purpose of this function. It can be used to create a popular arrangement of site elements in two, three, four columns. In fact, the Float CSS property applies to almost any html element. Knowing the basics of editing the arrangement of elements using the Float function and then Property, creating any website design will not be difficult.

    Special programs of layout designers can sometimes not notice images, but go on top of them. Quite similar things happen in web design, only taking into account that the text, instead of climbing onto the image, is displayed (if the Float property is used incorrectly) next to it or below it, but always not where the developer needs it.

    CSS Float property description

    In fact, knowing how to use the Float property is a very good ace up the sleeve for any web designer. But, unfortunately, a lack of understanding of how this function works can lead to collisions of site elements and other similar frustrations. Previously, similar situations also occurred due to bugs in browsers. Now the secret of how to properly use the Float property will be revealed, and no more problems should arise with this.

    The Float property has four values:

    • Float:inherit;
    • Float:right;
    • float:left;
    • Float:none;

    For those who know English, the values ​​of the Float property parameters should be clear. But for those who don't know, here's a little explanation. Parameter :left; Moves the element's body to the far left corner of the parent element. The same thing happens (only in the other direction) with the bcgjkmpjdfybb parameter :right;. Meaning :inherit; tells the element to take on the same settings as its parent. Such elements are also called child elements, since they are located directly inside the parent in the html code. A property :none; allows the element not to disrupt the normal flow of the document, it is set by default for all parts of the code.

    How does Float work?

    The Float CSS property works quite simply. Everything that was described above can be done without much difficulty. Then everything will be just as simple. But before we continue studying the Float property, it's worth understanding a little theory. Every element of a website is a block. You can easily verify this by opening the console in Google Chrome by pressing Ctrl + Shift + J. The text, title, image, links and all other components of the site will be displayed in blocks, just different sizes. Initially, all these blocks come one after another. As you can see in the example below, the lines of code follow each other, so they will be displayed strictly one after another.

    This is called normal flow. With this flow, all blocks lie on top of each other (without intersecting the bodies of the elements) vertically. Initially, all the content of a web page is located in this way. But when using, for example, the CSS Float Left language property, the element leaves its natural position on the page and is floated to the far left. This behavior inevitably leads to a collision with those elements that remain in the normal flow.

    In other words, the elements, instead of being arranged vertically, are now next to each other. If the parent element has enough space so that it can accommodate two children inside itself, then a collision does not occur, but if not, then the overlap of one object with another is inevitable. This is extremely important to remember to understand how the CSS Float property works.

    Clear function to solve problems

    The Float function has a dear friend - Clear. Together they - Both of these functions complement each other and make the developer happy. As stated above, adjacent elements break out of their normal flow and begin to "float" as well, just like an element that has the Float property applied to it (for example, CSS Float Top). As a result, instead of one floating element, you get two, and not at all in the place where the developer intended to place them. From this moment all the problems begin.

    The Clear function has five values:

    • :left;
    • :right;
    • :both;
    • :inherit;
    • none;

    By analogy, you can understand when it is best to use the Clear function. If we have a line in the code Float:right;(CSS code is meant), then the function should be Clear:right;. The same applies to properties float:left; will complement it Clear:left;. When writing code Clear:both; It turns out that the element to which this function is applied will be located below the elements to which the Float function is applied. Inherit takes settings from the parent element, and none does not make any changes to the site structure. By understanding how the Float and Clear functions work, you can write unique and unusual HTML and CSS Float code that will make your website one of a kind.

    Using Float to Create Columns

    The Float property is especially useful when creating columns on a website (or centering CSS Float content on a web page). It is this code that is the most practical and convenient, so it is worth considering several options for creating a familiar site template consisting of two columns. For example, let's take a standard website with content on the left, a navigation bar on the right, a header, and a footer. The code will be like this:

    Now we need to figure out what is written here. The parent element, which contains the main part of the html code, is called a container. It allows you to prevent elements to which the Float function is applied from scattering in different directions. If it were not there, then these elements would float to the very borders of the browser.

    Then, in the code there are #content and #navigation. The Float function is applied to these elements. #content goes to the left and #navigation goes to the right. This is necessary to create a two-column site. It is necessary to specify the width so that the objects do not overlap each other. The width can also be specified as a percentage. This is even more convenient than in pixels. For example, 45% for #content and 45% for #navigation, and give the remaining 10% to the margin property.

    The Clear property, which is located in #footer, prevents the footer from following #navigation and #content, but leaves it in the same place where it was. What can happen? if you don't specify the Clear property? In this code, #footer will simply go up and end up under #navigation. This will happen because #navigation has enough space to accommodate one more element. This visual example clearly shows how the Clear and Float properties complement each other.

    Troubles you may encounter when writing code

    The above examples are quite simple. But problems can arise with them too. In general, in fact, a lot of unexpected troubles can happen with the Float function. No matter how strange it may be, problems usually arise not with the CSS, but with the html code. The place where the element with the Float function is located in the html code directly affects the operation of the latter. In order to avoid various kinds of difficulties, it is best to adhere to a simple rule - place elements with the Float function first in the code. This almost always works and minimizes their unexpected behavior.

    Collision of elements

    A collision occurs when a parent element containing multiple children cannot contain them all and they overlap each other. It even happens that elements may not be displayed, but disappear from the site. This is not a browser bug, but quite expected and proper behavior of elements with the Float function.

    Because these elements are initially in normal flow and then disrupted by the Float property, the browser may remove them from the site page. However, do not despair, because the solution is simple and clear - use the Cear property. It is possible that of all the ways out of this problem, using Clear is the most effective.

    But the problem of collision of web page elements can be solved in another way. There are at least two more ways:

    • using the Position function;
    • using Flexbox.

    The Position function is sometimes a good alternative to CSS Float. When using Position, it is best to place images in the center of the web page. If you apply the values:absolute and:relative correctly, the elements will fall into place and will not overlap each other.

    Analysis of the Position and Float function code

    It’s worth taking a closer look at how to replace Float with Position in HTML and CSS code. It's actually very simple. Let's say there is a #container and a #div element.

    In this example, using the (CSS Div) Float function in the second container will help create a standard two-column site. Never forget about the Clear function. Without it, you will only get elements superimposed on each other.

    So how do you change your CSS and Float code to use Postion? Very simple:

    position:relative;

    position:relative;

    In this case, #container and #div will take the position the developer needs in the parent element. Main? place #div and #container in one parent element that will match their sizes.

    Flexbox - how will this feature help replace CSS Float?

    Flexbox is the most advanced way to create websites at the moment, so this feature is not supported by older versions of browsers. This fact should not be discounted, because users with outdated versions browsers will not be able to see the correct version of the site.

    Flexbox is not a property, but a separate module. Therefore, flexbox supports a number of properties that work only with it. In addition, the display function, which has three parameters inline, block and inline-block in flexbox, has only one flex-flow left.

    How does Flexbox work?

    This technology will help the developer to easily align elements horizontally and vertically. Flexbox can also change the direction and order in which elements are displayed. This technology has two axes: Main axis and Cross axis, around which the entire Flexbox is built. It also removes the effect of the Float and Clear functions. It builds its system in code, in which it uses properties unique to it, so, unfortunately, it will not be possible to duplicate other properties, such as Float and Position, in elements. And this would be very useful, because, as mentioned above, Flexbox only works in new versions of browsers.

    It's worth remembering that in the end, Position, Flexbox and Float do the same thing - create an unusual and original design for your site. Each option discussed in the article does this in its own way and therefore has both advantages and disadvantages. In addition, it happens that somewhere the Float function is perfect (for example, in a site with a simple structure), but somewhere it is better to use Position or Flexbox.

    Double Margin Bug

    However, sometimes, unfortunately, every developer has problems related not to the written code, but to bugs in a particular type of browser. For example, there is a bug in Internet Explorer called the Double Margin Bug. It multiplies the Margin parameter by two, which leads to displacement of site elements beyond the boundaries of the browser. To avoid this, just specify the Margin parameter as a percentage. Typically this bug occurs when the values ​​of the Margin and Float properties match.

    margin-left:10px;

    This code will move the element in Internet Explorer 20 px to the left. You can change the code like this:

    margin-left:10%;

    or so,

    margin-right:10px;

    Both of these options will solve the problem of element displacement.

    Browser bugs and incorrect display of the site

    It is worth remembering that Internet Explorer is not the only browser in which bugs can occur. Old Google versions Chrome and Mozilla also display some elements of modern websites incorrectly. For each of these bugs, a solution can be found. In general, I would like to note that using Float will create an original and attractive website design. Understanding the basics and operating principles of this property will help you avoid mistakes and make life easier for any developer.

    In modern web design, the property float used at almost every step. But despite this prevalence, not everyone understands the mechanism of floating blocks, their behavior and what consequences their use may have.

    What is "float"?

    Float This is a CSS positioning property. To understand its essence and origin, you need to pay attention to the printed design. In printed layouts, the image may be positioned so that the text flows around it. This is usually called " text wrapping".



    In a page layout, a block that contains text can be specified to use wrapping text around an image or ignore the wrapping. Ignoring text wrapping will allow the words to flow over the image as if it were not there. This makes the difference whether the image is part of the flow on the page or not. In web design everything is very similar.



    In web design, an element with a CSS property applied to it float will behave like an image with text wrapping around it in a printed layout. Floating elements remain part of the flow of the web page. This is quite different from absolute positioned elements, which are removed from the flow, as if in a printed layout the text block was told to ignore image wrapping. Absolutely positioned elements do not affect the placement of other elements, and other elements do not affect their placement.

    Setting a property float for elements with using CSS as follows:

    #sidebar ( float: right; )

    There are four valid values ​​for the property float - left, right, none, inherit. The first two left And right indicate the direction of location - left and right, respectively. None- default value, indicates that the element is not floating and inherit instructing an element to inherit the value of a property float from the parent element.

    What is float used for?

    Beyond the simple example of wrapping text around an image, float can be used to create web layouts.



    Float, is also convenient to use for small layout elements. For example, let's take this small fragment of a web page. If we set the property float For a small avatar image, when the image size changes, the wrapping will change according to the new image dimensions:



    The same layout can be implemented using relative positioning of the container and absolute positioning of the avatar and text within it. But in a layout implemented according to this scheme, changing the image size will not affect the text block, since elements with absolute positioning do not affect other elements and other elements do not affect them.


    Wrap reset

    Clear related property to property float. Element with property set clear will not move upward around an element with the property set float, but will move downwards ignoring the flow. And again, an illustration that will explain everything without further ado.



    In the example above, the sidebar floated to the right of the main content block. The “footer” has moved to the free space under the sidebar, flowing around the block with the main content. To resolve this issue, you must specify a value for the footer's clear:both property to "clear" the flow around both columns.

    #footer ( clear: both; )

    Property clear has four meanings. Both used to relieve flow in both directions. Left And Right are used to reset one direction - left or right, respectively. None- default value. Inherit could be the fifth value, but it's surprisingly not supported Internet Explorer. Resetting only the left or right flow is quite rare, but has practical benefits.


    Great Collapse

    One thing about working with float What's puzzling is the effect this property has on parent elements. If the parent element contains no elements other than a float, then its height literally collapses. This isn't always noticeable, especially if the parent element doesn't have a prominent background, but it's important to keep in mind.



    But the alternative to such a collapse is even worse. Consider the following scenario:



    If the top block automatically expands to accommodate the floating element, we will end up with a gap in the flow of text between paragraphs, with no way to fix it. If this were so, then developers would complain much more often about this behavior of floating blocks than they do now about collapse.

    Collapse should always be kept in mind to prevent strange layout behavior and cross-browser issues. We can solve this problem using clear after the floating element in the container, but before the container closes.

    Wrapping Cancellation Techniques

    If you're in a situation where you know where the next element will be, you can use clear:both and go about your business. This is ideal since it does not require any hacks or additional elements. But unfortunately, usually not everything goes the way we want, and in this case you can use the following tools.

    Empty block method.

    It's literally an empty block.

    . Sometimes you can find an element
    or any other random element, but div is the most common since it has no default style in browsers, has no special function, and is unlikely to be in general CSS style. This method is rejected by semantic purists because its presence has no contextual meaning on the page and it is only there for appearance. Of course, in a strict sense they are right, but he does his job and does not harm anyone.

    Overflow method.

    Based on specifying CSS properties overflow for the parent element. If this property is set to auto or hidden for the parent element, it will expand after the floating element, effectively resetting the wrapping of subsequent elements. This method can be semantically beautiful, since it does not require additional elements. However, as you can see we have added a new div to use this method, which is equivalent to using a non-semantic empty block and is less flexible. It should also be remembered that the property overflow is not intended to disable wrapping. Be careful not to accidentally hide content or cause unwanted scroll bars.

    Easy cleaning method.

    Uses a CSS pseudo-selector (:after) to remove wrapping. Instead of using the property overflow For the parent element, set an additional class for it, for example "clearfix" and use the following CSS style:

    Clearfix:after ( content: "."; visibility: hidden; display: block; height: 0; clear: both; )

    This uses a small piece of content hidden from view, located after the parent element, which resets the wrap. This method is not complete, since it needs to be improved to support older browsers.

    Different situations require different bluff relief methods. Let's take as an example a grid of different types of blocks.



    To better visually combine similar blocks, we should start a new line when the color changes. We can use the overflow or light clearing method if each color group has a parent element. Or we use the empty block method between groups. Three parent blocks that did not previously exist or three empty blocks that did not previously exist. It's up to you to decide which method is better.


    Problems with floating elements

    Floating elements are often criticized due to their fragility. Much of this fragility comes from IE6 and its float-oriented bugs. But as more and more developers drop support for IE6, you may not think about it, but for those who care about compatibility, here's a short list.

    Pushdown, is a symptom that the element inside the floating block is wider than that block (this usually happens with images). Most browsers will render the floated element sticking out, but this will have no effect on the layout. IE will expand the floating block and often this has a drastic effect on the layout. A typical example is an image sticking out from a block with the main content, squeezing out sidebar down.



    Fast decision Problems: use overflow: hidden; to trim off excess.

    Double margin bug- another thing to remember when working with IE6. This bug is expressed in the fact that if the field is on the same side as it is oriented float, the field is doubled. For example:

    We will get the left field in 40px., instead of 20px.

    Quick solution to the problem: Set display: inline for the floating block, and don't worry the element will remain block-level.

    3px Jog. The essence of this bug is that the text located next to the floating element is strangely shifted by three pixels, as if under the influence of a force field located around the floating element. Quick solution to the problem: Set the width and height of the affected text.

    Appears in IE7 Bottom margin bug, when the parent element is a floating element and its child located inside it is also a floating element. The bottom margin (margin-bottom) of the child is ignored by the ancestor element. Quick solution to the problem: Use padding-bottom on the parent element instead of margin-bottom on the child element.

    Description

    Determines which side the element will be aligned to, with other elements flowing around it on the other sides. When the float property is set to none , the element is rendered on the page as normal, but it is allowed that one line of wrapping text may be on the same line as the element itself.

    Syntax

    float: left | right | none | inherit

    Values

    left Aligns the element to the left, and all other elements, such as text, flow around it to the right. right Aligns the element to the right, with all other elements flowing around it to the left. none The element's wrapping is not set. inherit Inherits the value of the parent.

    HTML5 CSS 2.1 IE 9 Cr 15 Op 11 Sa 5 Fx 8

    float

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat.
    Duis autem dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit au gue duis dolore te feugat nulla facilisi.


    Result this example shown in Fig. 1.

    Rice. 1. Using the float property

    Object model

    document.getElementById("elementID ").style.styleFloat

    document.getElementById("elementID ").style.cssFloat

    Browsers

    In Internet Explorer 6, there is an issue with doubling the left or right padding value for floating elements that are nested within parent elements. The margin that is adjacent to the parent's side is doubled. The problem is usually solved by adding display: inline to the floated element. This browser also adds a 3px padding (the so-called “three-pixel bug”) in the direction given value float

    Internet Explorer versions up to and including 7.0 do not support the inherit value.

    Float is a CSS property for positioning elements. In order to understand its purpose and origin, you can turn to print design. In a print layout, images can be positioned on the page so that text "flows" around them. This is usually called “text wrapping”.

    In page layout programs, elements with text can take into account images, as well as ignore them. If they are ignored, the text will appear above the pictures as if they were not there. This is the main difference between whether images are part of the main flow of the page or not. Web design is very similar.


    In web design, page elements with the float property set behave exactly like images in print when text "flows" around them. Such elements are part of the main flow of the web page. However, things are different if elements use absolute positioning. Absolutely positioned elements are removed from the main flow of the page, similar to the example above where in printing text ignores images. Such elements do not affect the position of other elements, whether they touch or not.

    Setting the float property works like this:

    #sidebar ( float: right; )

    There are a total of 4 values ​​for the float property. Left and right are used for corresponding directions. None (default) - ensures that the element will not float. And inherit , which says the behavior should be the same as the parent element.

    What can float be used for?

    In addition to wrapping text around images, float can be used to create the layout of an entire site.


    The float property is also useful on a smaller scale. For example, consider a small area on a website page. Let's say you use float for your avatar, when you change the image size, the text size will be adjusted to fit the image.


    The same arrangement of objects can be achieved by using positioning. The container object is assigned relative positioning, and the image object is assigned absolute positioning. In this case, the avatar will not affect the position of the text.


    Disabling the float property

    For float, the related property is clear. Any element that has the clear property set will not be floated to the top as expected, but will appear below the float elements. Perhaps an example in a picture will explain better than words.


    In the example, the sidebar is floated to the right (float: right;), and its height is less than the main content area. Therefore, the footer will be raised higher because it has enough height and the float behavior requires it. To fix the situation, it needs to set the clear property, which ensures that the element is displayed below float elements.

    #footer ( clear: both; )

    The clear property can have four values. Both, the most commonly used, is used to cancel the float of each direction. Left and Right - used to cancel the float of one of the directions. None - default, usually not used unless clear is needed. inherit would be the fifth value, but it is strangely not supported in Internet Explorer. Canceling just a left or right float is much less common, but certainly has its purposes.


    Great Collapse

    Another amazing thing about the float property is that its use can affect the parent element. If such an element contains only float elements, then it literally collapses, that is, its height is zero. This is not always noticeable unless the parent element has some kind of visible background set.


    This collapse seems illogical, but the alternative is even worse. Consider this example:


    If the block element at the top automatically expands to accommodate all the float elements, we'll end up with an unnatural gap in the text between paragraphs, with no way to fix it. If this were the case, our designers would complain much more often about this behavior than about the collapse.

    Thus, collapsing is almost always necessary to prevent layout difficulties. To change this behavior, you need to add a float canceling element after the float elements, but before closing the parent element.

    Ways to cancel float

    If you know that after float elements, some other element (for example, a footer) will always be displayed, then you just need to set the property clear: both; , as in the example above, and continue to do your own thing. This is ideal because it does not require any hacks or additional elements. Of course, not everything in our life is so smooth and there are times when this method is not enough. Therefore, it is necessary to have several additional methods in your arsenal.

    • Empty div method. A literally empty div is used.
      . Sometimes an element can be used in its place
      or whatever, but div is used most often because by default it has no style, no special purpose, and is unlikely to have a general style applied to it via CSS. Fans of semantically pure markup may not like this method, since the presence of an empty div has no contextual meaning and is placed on the page only for design reasons. Of course, strictly speaking, they are right, but he is doing his job and not harming anyone.
    • Overflow method. Based on the fact that the parent element needs to set the overflow property. If this property is set to auto or hidden , the parent element will expand to accommodate all float elements. This method looks more semantically correct since it does not require additional elements. However, if you were to use another div just to use this approach (meaning the parent div), then it would be the same as the previous example with adding an empty div. Also, remember that the overflow property has a different purpose. Be careful and don’t allow some of your content to disappear or unnecessary scroll bars to appear.
    • Simple cleaning method. This method uses the wonderful CSS pseudo selector :after. Much better than using overflow on the parent element. You simply give it an additional class, declared like this: .clearfix:after ( content: "."; visibility: hidden; display: block; height: 0; clear: both; ) This method adds invisible content and cancels float And by the way, this is not the whole story about how additional code should be used in older browsers.

    And, as you understand, each method is used in different situations. Let's take, for example, a mesh of block elements, different types.


    For a better visual presentation, it would be nice to combine similar blocks. For example we want each type to start with new line, in our case, the element type is determined by color. We can use the overflow method or the "simple clearing method" if each group has its own container element. Or we can use the empty div method between each of the groups. Three container elements, or three empty divs, which is better for your task is up to you.


    Problems with floats

    People often try to bypass Floats because they need to be worked with very carefully. Most of the bugs came with IE6. As more and more web designers stop supporting IE6, you may not be concerned about these issues. But for those who care, here's a short list.


    Alternatives to float

    If you need text to wrap around a picture, there are no alternatives. But for page layout, there are definitely choices. There are some very interesting approaches that combine the flexibility of float with the power of absolute positioning. CSS3 has something called Template Layout Module, which will provide a worthy alternative to float in the future.