Confused about missing width and/or height attributes

7,418

Solution 1

Adding the height and width attributes to your IMG SRC HTML tag allows the browser to know how much space to leave for an image. Without these values, the browser gives an image no space until the image is loaded, which means anything surrounding the image is adjusted after the image has loaded. http://www.computerhope.com/issues/ch001158.htm

Solution 2

The browser requests this for performance. Say you have a paragraph of text with an image of 100x100 pixels in the top left corner.

  • Browser builds the page, no image yet, so it builds it with just text
  • The image now loads, and suddenly there's space needed
  • Browser rebuilds the page, with the proper room for the image

If you give width and height to the image, it'll go like this:

  • Browser builds the page, no image yet but has sizes, so it builds it with the right clearance.
  • The image now loads, place it in the reserved holder

It saves the rebuild. A rebuild takes a little time, which can be noticed on mobile devices. It also costs a little performance, memory and CPU, which are limited on mobile devices. In the example above it's just 1 image, but when you have 20 images, you'll notice this.

The tricky part is when you also want to be responsive, then sometimes it's not very comfortable to add an size. I tend to add as much as I can without limiting myself (e.g. sometimes only a height/width, sometimes none).

Share:
7,418

Related videos on Youtube

cnayak
Author by

cnayak

Updated on September 18, 2022

Comments

  • cnayak
    cnayak over 1 year

    So I tested my site on https://gtmetrix.com and it said:

    The following image(s) are missing width and/or height attributes.
    

    I'm confused by this, because the images itself already have the correct width and height. So why would I want to add these attributes?

  • cnayak
    cnayak almost 9 years
    Then what should it be?
  • Arne Kröger
    Arne Kröger almost 9 years
    @WilliamD.Edwards While this answer is correct, it is not a requirement or invalid to leave them out, and I'm assuming your test result was not from the W3C validator.
  • Tim Fountain
    Tim Fountain almost 9 years
    The values for width and height attributes should match the dimensions of the image.
  • cnayak
    cnayak almost 9 years
    @TimFountain Wouldn't you be technically resizing it then?
  • Tim Fountain
    Tim Fountain almost 9 years
    No, the browser is smart enough to know that if dimensions in the <img> tag match the dimensions of the image file, no "resizing" is needed and it can be rendered as-is. It only needs to render it at a different size if the dimensions are different (which should basically never happen).
  • Martijn
    Martijn almost 9 years
    That javascript isn't responsive at all. It's a weird way of placing an image, that's it :)