Float and clear - CSS properties for floating elements in block layout. The concept of flow. Features of float

Float is CSS property for positioning elements. In order to understand its purpose and origin, you can refer to printing 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's 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 doesn't 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 ways in your arsenal.

  • Empty div method. A literally empty div is used.
    . Sometimes an element can be used in its place
    or some other, but div is used most often because by default it has no style, no special purpose and is unlikely to be applied to him general style 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 seems 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 a wonderful pseudo CSS selector- :after. Much better than using overflow on the parent element. You just set it to him additional class, declared like this: .clearfix:after ( content: "."; visibility: hidden; display: block; height: 0; clear: both; ) This method adds invisible content and cancels the 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 of the methods is used in different situations. Let's take, for example, a grid of block elements of different types.


For better visual representation 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 absolute positioning. CSS3 has something called Template Layout Module, which in the future will provide a worthy alternative float

Let's see what happens to elements when the float property is applied to them:

  • The element “floats” and is pressed against the left (if float: left) or right (float: right) edge of the parent element or element that is also set to float
  • If an element cannot fit in a row with another element due to the width of the parent block, it will be moved down until there is enough space for it
  • Other block elements for which the float value is not specified behave as if the element with float is not on the page (the element has “floated”). The lines “know” that the element has floated and wrap around it
  • The width of a block set to float is determined by the content.

Let's look at an example. Uncomment the float: left property inside the CSS. Look at the result.

Replace float:left with float:right.

The float property is useful for allowing text to wrap around images. Consider an example:

Add a comment to CSS string file to the float: left property. See how the page layout will change. Replace float: left with float:right.

“Collapse” of the parent element when the “children” pop up

Let element two be placed inside element one. By default, height one will stretch across the content. As soon as we apply the float property to the two element, it floats, and the parent element one will not know that two exists. If two has no content, then its height is zero. This behavior is called "collapse". To prevent the parent from collapsing, either the min-height property is given to it - the minimum height, or a method is used: another block is added, for which the property is set:

1

This block is not visible on the page, but the clear:both property removes the wrapping of elements and stretches the parent to the height of the content.

Uncomment the float:left property in CSS. Look how the parent element behaves:

Consider an example using clear: both

So you have become familiar with the basic properties of float. Let's put our knowledge into practice.

Execute

Exercise 1. Add classes to images. In classes, specify the float:left property. Study how the page output will change.

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 tongue CSS programming 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. Modern features the third version allows you to do this.

Developers can also use more convenient options formatting, 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 frustrations this kind of. Previously also similar situations 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. 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, properties CSS language Float Left, 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 site (or layout) CSS content Float in the center of the 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, navigation bar(navigation bar) on the right, header and 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 different sides. 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 in #footer, does not give footer follow #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. On this clear example It's very clear 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 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 accommodate 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, the use of the function ( CSS Div) Float will help you create a standard two-column website. 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 separate module. That's why flexbox supports whole line 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 at the end of the day Position, Flexbox and Float do the same thing - create unusual and original design 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 value is Margin properties and Float matches.

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 you can find a solution. 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.

All elements that appear on an HTML page are nothing more than rectangles. And basically only two types:

  1. block (blok), which occupy the entire width where they are, and are separated from what is above and below them. For example this DIV tags,P,H.
  2. built-in (inline). For example, SPAN, STRONG, EM, A and IMG.

tables.

The role of the property increased after the transition from table layout to div layout. This is because float allows a web developer to include columns without having to resort to a table. It can take values right, left, but not center.

Previously, page layout was done using tables.

The role of the float property increased after the transition from table layout to div layout. This is because float allows a web developer to include columns without having to resort to a table. It can take values right, left, but not center.

Using the display: block; property or display: inline; we are converting one type of rectangle to another. For example, a UL list that has a number of LI blocks can be laid out horizontally:

  • PARAGRAPH
  • PARAGRAPH
  • PARAGRAPH
  • PARAGRAPH
  • PARAGRAPH
  • PARAGRAPH

When using the float property, the rectangle is block, but with characteristic feature: Its width will not span the entire content. For example, an h3 header looks like:

this is HEADER h3

If you ask him display property: inline;, then we will see that not only the width has changed, but also the distance above and below the element:

this is HEADER h3

But if I want to place the element on the right and add text-align:right; this time, then we get:

this is HEADER h3

And it’s completely different if float: right;. Please note that the distance above and below the element remains unchanged:

this is HEADER h3

How will the elements next to the title behave?

The top text remains unchanged because a floated element cannot be positioned above the line on which it is created.

this is HEADER h3

But the red text is located under the title and it will wrap around it without having any additional styles. And only the height of h3 will be overcome, the page will return to its natural order.


A B C D Several floating elements will follow the sequence of their location.

ABING text...


And the alignment is done along the very bottom edge of those letters that are on the same side.


A B C D If we walk so that the flow around the element stops from a certain moment (from here), the clear property is applied. We can add it to an empty tag


In order to evenly place several block rectangles, we give them the same width.


Block 1
Block 2
Block 3
Block 4
Where is the distance between blocks? If you set , then due to the fact that the floating elements will not have enough space, they will move down.
Block 1
Block 2
Block 3
Block 4
The issue is resolved by adding another DIV:
Block 1
Block 2
Block 3
Block 4

Tabular layout is very convenient and understandable, which is probably why its analogue display: table; appeared. The same form is obtained with less code.

Block 1
Block 2
Block 3
Block 4
, where border-spacing specifies the horizontal and vertical distance between cell borders.

Now you can see how the image gallery is built. I hope no one has forgotten.

text...

text...


Links to sources:

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.

brief information

Designations

DescriptionExample
<тип> Indicates the type of the value.<размер>
A && BThe values ​​must be output in the order specified.<размер> && <цвет>
A | BIndicates that you need to select only one value from the proposed ones (A or B).normal | small-caps
A || BEach value can be used independently or together with others in any order.width || count
Groups values.[ crop || cross ]
* Repeat zero or more times.[,<время>]*
+ Repeat one or more times.<число>+
? The specified type, word, or group is optional.inset?
(A, B)Repeat at least A, but no more than B times.<радиус>{1,4}
# Repeat one or more times separated by commas.<время>#
×

Values

left Aligns the element to the left, and all other elements, such as text, flow around it right side. right Aligns the element to the right, with all other elements flowing around it to the left. none The element's wrapping is not specified.

Sandbox

Winnie the Pooh was always not averse to a little refreshment, especially at eleven in the morning, because at that time breakfast had long ended, and lunch had not yet begun. And, of course, he was terribly happy to see that the Rabbit was taking out cups and plates.

img ( float: none ; )

Example

float

Behaviorism, no matter how paradoxical it may seem, illuminates the sublimated stimulus; for example, Richard Bandler used a change in submodalities to build effective states.

Result this example shown in Fig. 1.

Rice. 1. Using the float property

Object Model

An object.style.cssFloat

Note

IN Internet browser Explorer 6 has a bug with doubling the left or right padding value for floating elements 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

Specification

Each specification goes through several stages of approval.

  • Recommendation - The specification has been approved by the W3C and is recommended as a standard.
  • Candidate Recommendation ( Possible recommendation ) - the group responsible for the standard is satisfied that it meets its goals, but requires help from the development community to implement the standard.
  • Proposed Recommendation Suggested Recommendation) - at this stage the document is submitted to the W3C Advisory Council for final approval.
  • Working Draft - A more mature version of a draft that has been discussed and amended for community review.
  • Editor's draft ( Editorial draft) - a draft version of the standard after changes were made by the project editors.
  • Draft ( Draft specification) - the first draft version of the standard.
×