William
William

Reputation: 451

HTML Image Width And Height Attributes

I have really simple question, I hope to read some great recommendations :-)

enter image description here

What is the correct usage of the width and height attribute?
Assuming that I need display the image with the following width and height: 150 x 100 pixles

<img src="..." alt="My Image" width="300" height="200" /> // the real width and height

or

<img src="..." alt="My Image" width="150" height="100" /> // the desired width and height (also defined in CSS)

Upvotes: 0

Views: 2197

Answers (3)

DracSkywalker
DracSkywalker

Reputation: 364

Width and height in img tag are used to display the image in desired size. If we set the width and height of an image. the image will displayed on the web page in specified width and height. If we want to display image in a size differ from actual size, the image will re size to the specified width and height. If width and height not specified, image will displayed in actual size. Most cases we don't need to specify img height. It will keep aspect ratio if width is specified. So if you want to display image in 150px x 100px you can use

<img src="..." alt="My Image" width="150px" height="100px" />

or

<img src="..." alt="My Image" width="150px" />

Also you can use % to specify the size in HTML4. That meas it spans specified percentage of the total area of its parent.

 <img src="..." alt="My Image" width="50%" />

But in HTML5 you should specify the dimensions in pixels.

Upvotes: 0

Aameer
Aameer

Reputation: 1376

Usually one would like to maintain the aspect ratio of the image. So you can do like this

<img src="..." alt="My Image" width="150"/> 

which will get the height to 100 in this case.Hope that helps.

Upvotes: 0

Le-roy Staines
Le-roy Staines

Reputation: 2057

You should display width/height as the size in pixels on the screen.

w3schools HTML width attribute documentation

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).

The actual dimensions of the image is not relevant. The browser will handle accordingly.

Upvotes: 1

Related Questions