1

I need to get the combined width of the images within a div and apply that width to the div. Im using this code from here:

Take combined width of multiple images and apply to their containing div

$(document).ready(function() {
    $('div').each(function() {
        var totalImageWidth = 0;

        $("img", this).each(function () {
          totalImageWidth += $(this).width();
        });

        $(this).width(totalImageWidth);
    });
});

This works fine until I apply padding to the images. Then the containing div is too small, as the images are taking up more space.

To try and fix this I've changed "img" to the image's containing div. So this: ("img", this) becomes this: ("div-which-is-around-image", this).

For some reason the containing div is now far too wide. I've no idea why this is happening. I changed dom ready to window load incase the issue was the images not being loaded in time, but it makes no difference.

Thanks

Community
  • 1
  • 1
Evanss
  • 23,390
  • 94
  • 282
  • 505

2 Answers2

0

You can use the innerWidth() method instead of width() wich return the widht including padding (excluding border and margin) Your code should look like this:

$(document).ready(function() {
    $('div').each(function() {
        var totalImageWidth = 0;

        $("img", this).each(function () {
          totalImageWidth += $(this).innerWidth();
        });

        $(this).width(totalImageWidth);
    });
});
ArtoAle
  • 2,939
  • 1
  • 25
  • 48
0

Oops, I was floating the image left but not its div. Floating them both has fixed this. Thanks

Evanss
  • 23,390
  • 94
  • 282
  • 505