April 6, 2012

Why aren't these two divs displayed how I expect them to be?

Question by Bogdan

This jsfiddle example shows what I’m talking about, I gave the div in question a red border to show how it’s displayed.

I’d expect the #searchwrapper_3 div to go inside the #col_st_cautare one, but for some reason that’s not how it works. I’ve been staring at it for a while now and I got no idea why it’s showing like that

I also have an example of it looking ok simply because i’ve added another element after the #searchwrapper div here.

Issue’s fixed, TIL a div will collapse if it contains only floating elements.

Answer by Dutchie432

You need to do a clear:both; – see the end of http://jsfiddle.net/wzYry/3/

<div style="border: 1px solid red;" id="col_st_cautare">
    <div style="float: left;" id="searchwrapper_3">

        .... code ....

    </div>
    <div style="clear:both;"></div>
</div>​

On a side note, it may be easier to make clr class in your styles.

.clr{clear:both;}

This way you can use this anytime you need to clear

<div class='clr'></div>

Answer by Starx

This is happening because the child elements inside are floated and parent lost track of the how to wrap them.

Probably the easiest fix for this

#col_st_cautare { overflow: hidden; }

Demo

Other than this, the stable solution would be to add <div style="clear:both;"></div> before the closing the element.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!