CSS

How to solve the float on the element itself in CSS

July 19, 2021

How to solve the float on the element itself in CSS

Previously to solve the float, aka not break the layout, it was necessary to create a new element just to clean the float in CSS, now with this technique we don’t need to mess the HTML anymore!

clean the float in CSS cover

Theory of solving the float

To solve this problem with the element that has the floats, we must first have a component structure.

This structure consists of a container, a simple div, which will house these elements that have float in our layout.

And then this parent element will have a :after pseudo-element, which is the key to solving the problem.

In this :after we’re going to add some empty content, which will simulate the div we would add in the old way in HTML and then we put a clear:both on it, simple right? 😀

Solving the float in practice

First, let’s see how the float can harm the layout if it’s not treated

Here is the code and the result:

<!-- HTML -->
<div id="float-container">
    <div class="float-div">
    </div>
    <div class="float-div">
    </div>
</div>
<div id="continuing-layout"></div>

/* CSS */
body {
    margin: 50px;

.float-div {
    width: 100px;
    height: 100px;
    background-color: red;
    margin-right: 20px;
    float: left;
}

#continuing-layout {
    height: 50px;
    width: 300px;
    background-color: magenta;
    position: relative;
}

Result:

Imagem

The non-float div took the front of the float div, and that’s what happens when we don’t handle the float correctly.

Now with the following addition of CSS, see how the layout behaves:

/* CSS addition */
#float-container:after {
     content: "";
     display: block;
     clear: both;
}

Result:

Imagem

Note that now, with the correct technique, the result of the layout is what is expected of the flow that the HTML represents, easy isn’t it? 🙂

We no longer need to mess up the HTML with a ‘useless’ div, thus making our code easier for future maintenance and also easier to understand.

Conclusion

We saw that the technique consists of adding a pseudo-element :after, in the container that holds the floated elements.

And then apply the necessary empty content rules, so that this same float div is in charge of cleaning the float.

And that’s it for clean the float in CSS, see you in next post!

Also take a look at our YouTube channel by clicking here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x