Clean up floating elements correctly

I am trying to create a panel in which all elements float. I don't have a problem with this part, but the problem is that when I try to add a new block below that, I either have a space before the first element in this new block, or a space between my two blocks when I add clear: both;

.

I've already tried with the new clearfix, but it doesn't work in my case.

Here's a little code I did to show you the problem: http://codepen.io/anon/pen/piDEK . I wish I had no space between my two blocks and my h1 should be on the left (not after my ul, you can try deleting clear

it in my codep) obviously.

Thank you for your help.

+3


source to share


4 answers


Use clear before closing each parent element that is like a floating child.

Use

<div class="clear"></div>

      

& CSS

.clear{clear:both;}

      



I used this after the last one li

, after ul

and after the .top-bar

div.

Edit:

The white line between the two divs is related to the #top-bar #left-menu li

element's line-height greater than the parent's height. Use

#top-bar #left-menu li {line-height:63px;}

      

Here's a codepen change for example. DEMO

+1


source


You can always add overflow:hidden;

in #topbar

(and / or #content

) then remove the individual cleanup div

, so the revised CSS will look like this:

#top-bar {
    width: 100%;
    height: 65px;
    /* border: 1px solid #e6e6e6; */
    padding: 0 25px;
    background: green;
    overflow:hidden;
}

      

The goal overflow:hidden

is not to clear the floats as such, but to control the protection of the content of the content by creating a new block formatting context (BFC), one of the features of BFC is float containment.



More on BFC from MDN

The block formatting context is part of the visual CSS rendering of the Web page. This is the area in which the layout of the blocks of blocks takes place and in which the floats interact with each other.

The block formatting context contains everything within the element creating it, which is also not inside the child element, which creates the new block formatting context.

Block formatting contexts are important for positioning (see float) and clearing (see clearing) of floats. The placement and clearing rules of floats only apply to things within the same formatting context block. Floats don't affect the placement of things in other block formatting contexts, and clear only clears whitespace in the same block formatting context.

+2


source


you can clear float

by pointing overflow:hidden;

to the parent element. check DEMO .

As in your case, use an element section

.

section{overflow:hidden;}

      

+2


source


Just add display:none

a clearfix DIV to the style to remove unwanted spaces.

<div style="clear: both; display:none"></div>

You will most likely have more than one of these on your site, so I would recommend using a class instead of inline style.

-2


source







All Articles