J. Soukup
J. Soukup

Reputation: 45

calculate element width based on first line of children

So I have a code like this

This is supposed to be a responsive grid of images and for the last element on a line, the class .last is added by jQuery so it has no margin-right. (solution from here)

But now, I need to assign width to the <section class="grid"> based on the width of the first line of elements for margin: 0 auto to work.

I tried this:

var width = 0;
$('section.grid img').each(function() {
    width += $(this).outerWidth( true );
});
$('.grid').css('width', width);

but obviously that doesn't work as it sums all the elements, not just the first line. Also the number of images on a line is variable based on the screen width.

Thank you.

Upvotes: 2

Views: 84

Answers (1)

Pugazh
Pugazh

Reputation: 9561

Here are the steps:

  1. Get the width of window and outerWidth(width + padding + margin) of img
  2. Calculate the no of img that can fit into the window.
  3. Apply the calculated width (no of img's that can fit * it's width )

Updated fiddle

Width for <section class="grid"> can be calculated by parseInt(winWidth / width) * width

Upvotes: 1

Related Questions