Search code examples
csscss-floatclearfix

Clear fix problems with overflow and pie-clearfix


I am trying to float some elements and apply clearfix so that the parent element can expand to the height and width of the children.

So, I simply set up the layout as per this fiddle: http://jsfiddle.net/fMjEx/

I then wanted to float the elements inside .bar. This is usually quite straight forward:

  1. Float the elements.
  2. Clear fix the parent using pie-clearfix or overflow: auto.

However, I ran into these problems:

  • If I use pie-clearfix, the element .picture which is next to .bar is also included in the clearing: http://jsfiddle.net/6C7WD/

  • If I use overflow: auto or overflow: hidden, the width of the .bar no longer spans the width of the document: http://jsfiddle.net/fv2gA/

Initially, one solution I had was to make .picture position: absolute. However, the problem with this approach is that the element is taken out of the flow.

In the layout, the height of .bar is variable depending on the content inside. I would like to give .bar and .picture a margin-bottom so that anything that comes after them is pushed downwards by that amount depending on whether .bar or .picture has a greater height.

This rules out using position: absolute on .picture as a solution.

Are there any solutions that satisfy the following?

  • Clear only floats within .bar.
  • Does not remove any elements from the flow.

Solution

  • This is the solution I ended up with:

    Added a wrapper to the markup:

    <div class="container">
    
    <div class="group"> <-------------------------- This is the wrapper
        <div class="picture"></div>
        <div class="bar">
            <div class="info"> some text goes here</div>
            <div class="buttons">some other content goes here</div>
        </div>
    </div>
    </div>
    

    And the CSS:

    .picture{
        width: 100px;
        height: 100px;
        float: left;
        background: green;
        margin-left: 100px;
        margin-top: 10px;
        z-index: 2;
        position: relative;
    }
    
    .bar{
        background: blue;
        margin-top: -80px;
        overflow: auto;
        width: 100%;
        float: left;
        z-index: 1;
        position: relative;
    }
    
    .group{
        margin-bottom: 10px;
    }
    
    .group:after {
        clear: both;
        content: "";
        display: table;
    }
    
    .info, .button{
        float: left;
        margin-left: 200px;
    }
    
    .container{
        overflow: auto;
    }
    

    Fiddle of the above: http://jsfiddle.net/c6Lng/