Code Example

<img src="/wp-content/uploads/flamingo.jpg" width="640">

Controlling Image Width

Before the advent of CSS, the display width of an image was controlled by the width attribute. This usage has been deprecated. In the absence of any CSS rules defining the display width of the image, it will still work in most browsers. However, this is specifically contrary to the HTML5 specification.

<!-- This works, but you shouldn't do it. --> <img src="/wp-content/uploads/very-large-flamingo.jpg" width="500">

Control Image Size with CSS

Responsive Image Widths

Generally speaking, you usually don't want to control the exact width of an image. Every visitor who comes to your website has a potentially different size screen. If you specify the width, it may be much too small for some users and much too big for others. Most of the time, the best option is to make sure that your image is inside of a responsive (percent-based) container and then let it fill the container.

Informing the Browser — the actual purpose of width

The actual purpose of the width attribute, according to the specification, is to inform the browser of the actual, intrinsic width (in CSS pixels) of the image file. In other words — the width attribute should be used to describe the source file, not how you want it displayed. This information can then be used by the browser in optimizing the rendering. This means that if you use CSS the way should, then the CSS — and not the width element — will determine the actual display size of the image.

Note: On most screens, the image would overflow the container if it was actually 1280 pixels wide.

Should I use width?

Yes. It is not essential, but it will help the browser render your page faster and more cleanly, especially when combined with the height element. Consider the example above — the CSS width is set to 100% and the height is set to auto. Until the browser is able to download the entire image, and check the file header for its size, how does the browser know how much height to allot for the image? In the absence of a widthandheight attribute, it doesn't. However, if both are specified, the browser can do some math to figure it out:

display_height = img_height × ( display_width ÷ img_width )

Doing this will stop that annoying jump that happens when a freshly loaded images suddenly takes up space in the document and shoves all the content down, causing the user to lose their place on the page. So yes, use the width (and the height) attribute. But use it correctly — to identify the intrinsic height of the image file, not to specify the desired layout size.