Steven Morgan
Steven Morgan

Reputation: 77

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

HTML

<div class="box">
  <img src="http://placehold.it/250x150" />
</div>

JS

var img = $(".box > img");
$(".box").css({width:img.width(), height:img.height()});

So jquery get image dimensions, add inline style to .box with the width and height

Upvotes: 0

Views: 1656

Answers (2)

Jonathan Marzullo
Jonathan Marzullo

Reputation: 7051

Add this to your JavaScript requires jQuery

$(".box > img").css({width:250,height:250});

Using native JavaScript, but you need to give the image an ID

var myImg = document.getElementById('myImgID');
myImg.style.height = '250px';
myImg.style.width = '250px';

UPDATED AFTER QUESTION CHANGED ABOVE:

@Gugic got the right answer above after question was edited :)

Upvotes: 2

Gugic
Gugic

Reputation: 109

jonathan didn't get it right. His solution not about what was asked. Correct one is

var img = $(".box > img");
$(".box").css({width:img.width(), height:img.height()});

Upvotes: 3

Related Questions