Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to specify image dimensions for fastest rendering: in HTML or in CSS?

I've learned that it is a best practice to explicitly specify image dimensions. The browser can then already layout the page while still downloading the images themselves, thereby improving (percieved) page rendering time.

Is this true? And if so, is there a difference in specifying the dimensions in either HTML or CSS?

  • HTML: <img src="" width="200" height="100">
  • Inline CSS: <img src="" style="width: 200px; height: 100px">
  • External CSS: #myImage { width: 200px; height: 200px; }
like image 320
Daan Avatar asked Dec 22 '09 15:12

Daan


People also ask

Is it better to resize an image in HTML or CSS?

It's usually better to use CSS to resize images in HTML. You can do this with the height and width properties. This image is resized using the CSS 'width' and 'height' properties.

How do I change the rendered image size in CSS?

You can override this by setting the height and width using the background-size CSS property. You can scale the image upward or downward as you wish. Possible values of background-size : auto - Renders the image at full size.

How do I change the size of the render image in HTML?

Step 1: Firstly, we have to type the Html code in any text editor or open the existing Html file in the text editor in which we want to change the size of an image. Step 2: Now, place the cursor inside the img tag. And then, we have to use the height and width attribute of the img tag for changing the size of an image.

Which attribute is used to specify image dimensions?

The width attribute specifies the width of an image, in pixels.


1 Answers

According to Google Page Speed, it does not really matter if you specify the dimensions via CSS or HTML, as long as your CSS targets the IMG tag itself and not a parent element :

When the browser lays out the page, it needs to be able to flow around replaceable elements such as images. It can begin to render a page even before images are downloaded, provided that it knows the dimensions to wrap non-replaceable elements around. If no dimensions are specified in the containing document, or if the dimensions specified don't match those of the actual images, the browser will require a reflow and repaint once the images are downloaded. To prevent reflows, specify the width and height of all images, either in the HTML tag, or in CSS.

However, note that they advise not to resize the image using these dimensions, ie to always use the real dimensions :

Don't use width and height specifications to scale images on the fly. If an image file is actually 60 x 60 pixels, don't set the dimensions to 30 x 30 in the HTML or CSS. If the image needs to be smaller, scale it in an image editor and set its dimensions to match (see Optimize images for details.)

like image 119
Wookai Avatar answered Sep 18 '22 14:09

Wookai