- This topic is empty.
Viewing 8 posts - 1 through 8 (of 8 total)
Viewing 8 posts - 1 through 8 (of 8 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › jQuery Get Image Dimensions, Apply To Div
I want a div to get an inline style of the image it wraps around.
Pen here: http://codepen.io/stevenmorgan94/pen/xuEwm
So jquery get image dimensions, add inline style to .box with the width and height
You can do this will CSS.
Just set the div to display:inline-block
.
Thanks Paul, I know that. My reasoning for doing it dynamically is I have clients adding photos of different sizes into a box. So I need jQuery to determine that size and apply it to the div that wraps the image.
And the box has to have exactly dimensions because of the jQuery plugin I’m using that centers it on the page.
Ah I figured it out
var img = $(".box > img");
$(".box").css({width:img.width(), height:img.height()});
Hiya Steven. The solution you posted won’t work if there are multiple .box
elements on the page containing different-sized images.
You want something more like this:
// For each .box element
$('.box').each(function() {
// Set up the variables
var $this = $(this),
w = $this.find('img').width(), // Width of the image inside .box
h = $this.find('img').height(); // Height of the image inside .box
$this.width(w).height(h); // Set width and height of .box to match image
});
http://codepen.io/JoshBlackwood/pen/kLDoI
Edited to add: If you’re only going to have one .box
on a given page, then your solution will be fine. Mine is simply more futureproof and flexible, at the cost of a few more lines of code.
Perfect, thanks man.
No problem, glad to help!