SamFisher83
SamFisher83

Reputation: 3995

what is the difference between img.height vs img.style.height?

I am trying to resize a bunch of images by going through an array and resizing them

if(items[0].height > 700 || items[0].width > 700){
  items[0].style.height = "700px";
   items[0].style.width = "700px";
}

When I am playing with canvas trying to crop images I notice that that coordinates I give it to crop aren't cutting what I would expect.

I am going assume that img.style.height only changes display properties and img.height changes the actual dimensions of the img? or do they do the same thing?

Upvotes: 1

Views: 1646

Answers (2)

Ben McCormick
Ben McCormick

Reputation: 25728

img.height refers to the height attribute on the element, img.style.height refers to the height defined as a style (like in css)

for

img.height will be 20.

for

<img id="example" style="height:20">

img.style.height will be 20. If you're setting the style generally its better to prefer using styles and separating out your concerns over hardcoding the heights as attributes. So in this case probably set a class on the image and put the height in CSS.

If you're reading the styles, img.height will return the actual height no matter how its set, so its safer.

Upvotes: 3

exxodus7
exxodus7

Reputation: 562

The main difference I've found (other than the nature of the attribute as described by @ben336) is in what they can represent.

  • img.height will always represent the height in pixels. This is only true in HTML5, which is what I'm guessing you're using based on your tags. Earlier versions of HTML allow both percentage and pixels to be specified by img.height, making my point moot.

    img.height = 20; // Always means 20 pixels.
    
  • img.style.height on the other hand will represent the height either in pixels or as a percentage of the original size.

    img.style.height = 20px; // 20 pixels in height;
    

    or

    img.style.height = 20%; // 20% of original height.
    

Upvotes: 1

Related Questions