HTML sizes Attribute
Description
The HTML sizes
attribute is used in conjunction with the srcset
attribute to specify a set of image sources for different display or device conditions for the <img>
, <source>
, and <link rel="icon">
elements. The sizes
attribute informs the browser about the size of the image for various breakpoints, allowing it to select the most appropriate image source from the srcset
based on the current viewing context. This is particularly useful for responsive web design, where the display size of an image might change based on the screen size, resolution, or other factors.
The value of the sizes
attribute is a comma-separated list of source size values. Each source size value consists of:
- A media condition (e.g., a media query) that describes a particular scenario, such as a certain viewport width. This part is optional; if omitted, the size value applies to all viewport widths.
- A source size value that specifies the width of the slot the image will fill when the preceding media condition is true. This value can be in pixels (e.g.,
300px
) or as a relative width (e.g.,100vw
for 100% of the viewport width).
Here is a basic example of using the sizes
attribute with srcset
:
<img srcset="small.jpg 500w,
medium.jpg 1000w,
large.jpg 1500w"
sizes="(max-width: 600px) 500px,
(max-width: 900px) 1000px,
1500px"
src="medium.jpg"
alt="Example image">
In this example:
- When the viewport width is 600px or less, the browser is advised to use the
small.jpg
image, which is best suited for slots up to 500px wide. - Between 601px and 900px in width,
medium.jpg
is suggested, fitting slots up to 1000px wide. - For viewports wider than 900px,
large.jpg
is recommended, with the slot width set at 1500px.
The sizes
attribute enhances the responsiveness of web content by ensuring that images are downloaded and displayed in the most size- and bandwidth-efficient manner possible, improving both the performance and the user experience.
Syntax
<tagname sizes="(media-condition) width">
Values
- (media-condition) widthA media-query followed by the image layout width. The layout width can be defined with px, em, or vw.
Applies To
The sizes
attribute can be used on the following html elements.
Example
<img
src="images/sunset1.jpg"
srcset="images/sunset480.jpg 480w, images/sunset768.jpg 768w, images/sunset1024.jpg 1024w"
sizes="(max-width: 480px) 480px, (max-width: 768px) 768px, 1024px"
alt="Responsive image"
/>
Browser Support
The following table will show you the current browser support for the HTML sizes
Attribute.
Desktop | |||||
![]() |
![]() |
![]() |
![]() |
![]() |
|
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 29th March 2024