How can I make the container div the same width as the floating children, and center it when there are several rows of floating children?

I have a div container with several floating child divs. Each child has the same width, but the size of the line depends on the width of the screen. I want the container to be only the width of its children, and also to be centered, everything dynamically depended on the size of the screen. This article explains a similar problem:

The div container changes width when adding a second row of floating children

Here is a fiddle that also explains the problem:

.centered { text-align: center; } .container { background: red; padding: 10px; display: inline-block; } .child { width: 100px; height: 100px; float: left; } .child:nth-child(even) { background: green; } .child:nth-child(odd) { background: blue; } <div class="centered"> <div class="container"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div> </div> 

http://jsfiddle.net/LxLjv3tm/1/

Here is another stackoverflow post that solves the problem for a single line:

The presence of elements of floating children determines the parental width

(the problem is that floating children are enough to create multiple lines)

+1
source share
1 answer

JQuery seems to be the answer. To "dynamically" set the width of the container div, we need to calculate the width of the event of the resize event through jQuery. We can use the width of the window and the width of the children to calculate the width of the inner container.

Here is the fiddle:

 var resizeContainerDiv = function() { var screenWidth = $(window).width(); var childWidth = $(".child").outerWidth(); var innerContainerWidth = Math.floor(screenWidth / childWidth) * childWidth; $('.container').css('width', innerContainerWidth); } $(window).on("load", resizeContainerDiv); $(window).on("resize", resizeContainerDiv).resize(); .centered { text-align: center; } .container { background: red; padding: 10px; display: inline-block; } .child { width: 100px; height: 100px; float: left; } .child:nth-child(even) { background: green; } .child:nth-child(odd) { background: blue; } <div class="centered"> <div class="container"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div> </div> 

https://jsfiddle.net/02arvnLx/1/

+1
source

All Articles