1
<img src="img_forest.jpg" alt="Forest" width="600" height="400">

I have the above line in my html body tag. But the height and width specified here are overridden by the height and width specified for the img in the stylesheet.

Why does this happen?

Deeven
  • 413
  • 1
  • 5
  • 14

4 Answers4

2

At this point your getting into more of styling the image element. The width and height attributes initially tell the browser the necessary amount of space it needs to make on-screen for these images when the page loads.

Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded. However, without these attributes, the browser does not know the size of the image, and cannot reserve the appropriate space to it. The effect will be that the page layout will change during loading (while the images load).

http://www.w3schools.com/TAgs/att_img_width.asp

Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
0

Try inline style to override your css file or more specified your css selector for images in your html page.

<img src="img_forest.jpg" alt="Forest" style='width:600px !important; height:400px !important;'>
oguzhancerit
  • 1,436
  • 1
  • 16
  • 27
0

That's because the width and height attributes set the intrinsic width and height of the image.

By default, width and height CSS properties have the value auto. Since images are replaced elements, this means the intrinsic sizes will be used (§10.3.2 and §10.6.2).

However, you can override that with some declaration, and then of course the image will be displayed with the specified size.

If you don't want this, add important inline styles, which can't be overriden:

<img src="img_forest.jpg" alt="Forest" width="600" height="400"
     style="height: auto !important; width: auto !important" />

img {
  height: 100px;
  width: 500px;
}
<img src="/favicon.ico" alt="Forest" width="16" height="16"
     style="height: auto !important; width: auto !important" />
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

You can see width="600" is an attribute, but width:100px is a property. While rendering these attributes are converted to the respective style and placed at the beginning of the style sheet.

Check the accepted answer Click here. This is what you want.

Community
  • 1
  • 1
Nandan Bhat
  • 1,573
  • 2
  • 9
  • 21