Kleajmp Kleajmp - 1 year ago 72
CSS Question

jQuery: give each <figure> parent the same width as its <img> child

Each image container (figure) needs to take the width of the image (img) it contains and place a (figcaption) with the same width as the container.

If I use only one container it works but when I use multiple figures it sets every figure with the size of the first image.

So I'm making a logical mistake in the foreach loop, but can't find a solution. Any help? I'm pretty new in jQuery.


//make figure the width of its image child
$('figure').each(function() {
var childWidth = $('figure img').width();

look at the html/css code

Answer Source

You are selecting and setting all figure elements width within .each(). Substitute

var childWidth = $("img", this).width(); // selects current `figure` `img`


var childWidth = $('figure img').width(); // selects all `img` elements


$(this).width(childWidth); // selects current `figure`


$('figure').width(childWidth); // selects all `figure` elements
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download