Distribute elements with gap between them evenly in parent div and change their width automatically

1.1k Views Asked by At

Problem: Div is 850px and has a variable number of child elements (image in link element). I want them to change their width automatically so they fill out the parent div having a 10px wide gap between them. Also they should be justified in the parent and the first and last child should have no gap to the left, respectively to the right.

Resizing and fitting works fine but I haven't got a clue how to get the gaps in there.

    $(".products a img").width($("#products_div").width() / $(".products a img").length);
1

There are 1 best solutions below

1
On

You need also to show us your CSS and your HTML markup on this type of problem for us to easily locate a conflict or error. A difference in display, setting a float or margin can produce a different result to what exact you are looking to do.

I believe this is your markup:

<div id="products_div" class="products">
    <a><img src="..."/></a>
    <a><img src="..."/></a>
    <a><img src="..."/></a>
    <a><img src="..."/></a>
    <a><img src="..."/></a>
    <a><img src="..."/></a>        
</div>

Your CSS would then be:

#products_div { width:850px;}
.products a img{ float:left; }

And this how you solve the images width and gaps with js/jquery:

var gap = 10;

var imgWidth = ($("#products_div").width() + gap) / $(".products a img").length;

$(".products a img").width(imgWidth - gap).css({'margin-right':gap}).last().css({'margin-right':0});

Here is the fiddle