February 18, 2013

Align width of container div to the sum of floating div

Question by Seb37

I have the following html:

<div class="main_container">
    <div class="sub_container">
        <div class="floating">wookie1</div>
        ...
        <div class="floating">wookie5</div>
    </div>
</div>

I want sub_container to have the exact width of the sum of the floating div.

If I use “display:table;” for sub_container and “display: inline-block;” for floating divs, it works fine:

enter image description here

until I have enough div in the list, so that the sum of width is larger than main_container and they break on the next line:

enter image description here

But still, I want subcontainer (yellow background) to to be ALWAYS the EXACT WIDTH of the sum of the divs, even when they go on several lines, like this:

enter image description here

I’ve googled for hours now, and wasn’t able to find an elegant solution (css only, if possible.)

Here’s the jsfiddle, to play with this.

Answer by Starx

I got bored trying this and created a JS script based on jQuery to solve it.

var t = $(".sub_container").width()/$(".floating").outerWidth();
$(".sub_container").width(parseInt(t) * $(".floating").outerWidth());

Demo

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!