Responsive images  |  web.dev (2024)

Text on the web automatically wraps at the edge of the screen so that it doesn'toverflow. Images, on the other hand, have an intrinsic size. If an image iswider than the screen, the image overflows and the user has to scrollhorizontally to see all of it.

Fortunately, CSS gives you tools to stop this from happening.

Constrain your images

In your style sheet, you can use max-inline-sizeto declare that images can never be rendered at a size wider than theircontaining element.

Browser Support

  • 57
  • 79
  • 41
  • 12.1

Source

img { max-inline-size: 100%; block-size: auto;}

You can apply the same rule to other kinds of embedded content too, like videosand iframes.

img,video,iframe { max-inline-size: 100%; block-size: auto;}

With this rule in place, browsers automatically scale down images to fit on thescreen.

Responsive images | web.dev (1)

Adding a block-sizevalue of auto means the browser preserves your images' aspect ratio as itresizes them.

Sometimes, an image's dimensions are set by a content management system (CMS) orother content delivery system. If your design calls for a different aspect ratiofrom the CMS's default, you can use theaspect-ratioproperty to preserve your site's design:

img { max-inline-size: 100%; block-size: auto; aspect-ratio: 2/1;}

Unfortunately, this often means the browser has to squash or stretch the imageto make it fit in the intended space.

Responsive images | web.dev (2)

To prevent squashing and stretching, use theobject-fit property.

Browser Support

  • 32
  • 79
  • 36
  • 10

Source

An object-fit value of contain tells the browser to preserve the image'saspect ratio, leaving empty space around the image if needed.

img { max-inline-size: 100%; block-size: auto; aspect-ratio: 2/1; object-fit: contain;}

An object-fit value of cover tells the browser to preserve the image'saspect ratio, cropping the image if needed.

img { max-inline-size: 100%; block-size: auto; aspect-ratio: 2/1; object-fit: cover;}
Responsive images | web.dev (3)Responsive images | web.dev (4)

You can change the position of the image crop using theobject-positionproperty. This adjusts the focus of the crop, so you can make sure the mostimportant part of the image is still visible.

Browser Support

  • 32
  • 79
  • 36
  • 10

Source

img { max-inline-size: 100%; block-size: auto; aspect-ratio: 2/1; object-fit: cover; object-position: top center;}
Responsive images | web.dev (5)

Deliver your images

Those CSS rules tell the browser how you'd like images to be rendered. You canalso provide hints in your HTML about how the browser should handle those images.

Hints for sizing

If you know your image's dimensions, always include width and heightattributes. Even if the image is rendered at a different size because of yourmax-inline-size rule, the browser still knows the width to height ratio andcan set aside the right amount of space. This prevents your other content fromjumping around when the image loads.

<img src="image.png" alt="A description of the image." width="300" height="200">

Hints for loading

Use the loading attribute to tell the browser whether to delay loading theimage until it's in or near the viewport. For images below the fold, use a valueof lazy. The browser won't load lazy images until the user has scrolled fardown enough that the image is about to come into view. If the user neverscrolls, the image never loads.

<img src="image.png" alt="A description of the image." width="300" height="200" loading="lazy">

For a hero image above the fold, don't use loading. If your site automaticallyapplies the loading="lazy" attribute, you can usually set loading to thedefault value of eager to prevent images from being lazy loaded:

<img src="hero.jpg" alt="A description of the image." width="1200" height="800" loading="eager">

Fetch Priority

For important images-such as the LCP image, you can furtherprioritize the loading using Fetch Priority bysetting the fetchpriority attribute to high:

<img src="hero.jpg" alt="A description of the image." width="1200" height="800" loading="eager" fetchpriority="high">

This tells the browser to fetch the image right away and at high priority,instead of waiting until the browser has finished its layout and would fetchimages normally.

However, when you ask the browser to prioritize downloading one resource, likean image, the browser must de-prioritize another resource such as a script or afont file. Only set fetchpriority="high" on an image if it's truly vital.

Hints for preloading

It's best to avoid preloading whenever possible by including all images in theinitial HTML file. However, some images may be unavailable, such as imagesadded by JavaScript or a CSS background image.

You can use preloading to get the browser to fetch these important images ahead oftime. For really important images, you can combine this preloading with thefetchpriority attribute:

<link rel="preload" href="hero.jpg" as="image" fetchpriority="high">

Again, use these attributes sparingly to avoid overriding the browser'sprioritization heuristics too often. Overusing them can cause performancedegradation.

Some browsers support preloading responsive imagesbased on srcset, using the imagesrcset and imagesizes attributes.For example:

<link rel="preload" imagesrcset="hero_sm.jpg 1x hero_med.jpg 2x hero_lg.jpg 3x" as="image" fetchpriority="high">

By excluding the href fallback, you can make sure browsers without srcsetsupport still preload the correct image.

You can't preload images in different formats based on browser support ofcertain formats. Attempting this can result in extra downloads that waste users'data.

Image decoding

There's also a decoding attribute you can add to img elements. You can tellthe browser that the image can be decoded asynchronously, so it can prioritizeprocessing other content.

<img src="image.png" alt="A description of the image." width="300" height="200" loading="lazy" decoding="async">

You can use the sync value if the image itself is the most important piece ofcontent to prioritize.

<img src="hero.jpg" alt="A description of the image." width="1200" height="800" loading="eager" decoding="sync">

The decoding attribute doesn't change how fast the image decodes. It affectsonly whether the browser waits for this image decoding to happen beforerendering other content.

In most cases this doesn't have much impact, but sometimes it can let thebrowser display your image or other content slightly faster. For example, for alarge document with lots of elements that take time to render, and with largeimages that take a long time to decode, setting sync on important images tellsthe browser to wait for the image and render both at once. Alternatively,you can set async to let the browser display content faster and withoutwaiting for the image to decode.

However, the better option is usually to try toavoid excessive DOM sizesand use responsive images to reduce decoding time, instead of using decoding.

Responsive images with srcset

Thanks to that max-inline-size: 100% declaration, your images can't break outof their containers. However, if a user has a small screen and a low-bandwidthnetwork, making them download the same size images as users with larger screenswastes data.

To fix this issue, add multiple versions of the same image at different sizes,and use the srcsetattribute to tell the browser these sizes exist and when to use them.

Width descriptor

You can define a srcset using a comma-separated list of values. Each value isthe URL of an image, followed by a space, followed by some metadata about theimage, called a descriptor.

In this example, the metadata describes the width of each image using the wunit. One w is the width of one pixel.

<img src="small-image.png" alt="A description of the image." width="300" height="200" loading="lazy" decoding="async" srcset="small-image.png 300w, medium-image.png 600w, large-image.png 1200w">

The srcset attribute complements the src attribute instead of replacing it.You still need to have a valid src attribute, but the browser can replace itsvalue with one of the options listed in the srcset. To save bandwidth, thebrowser only downloads the larger image if they're needed.

Sizes

If you're using the width descriptor, you must also use thesizesattribute to give the browser more information. This tells the browser what sizeyou expect the image to be displayed at under different conditions. Thoseconditions are specified in a media query.

The sizes attribute takes a comma-separated list of media queries and imagewidths.

<img src="small-image.png" alt="A description of the image." width="300" height="200" loading="lazy" decoding="async" srcset="small-image.png 300w, medium-image.png 600w, large-image.png 1200w" sizes="(min-width: 66em) 33vw, (min-width: 44em) 50vw, 100vw">

In this example, you're telling the browser that in a viewport with a width over66em, it should display the image no wider than one third of the screen(inside a three-column layout, for example).

For viewport widths between 44em and 66em, display the image at half thewidth of the screen (as in a two-column layout).

For anything narrower than 44em, display the image at the full width of thescreen.

This means that the biggest image won't necessarily be used for the widestscreen. A wide browser window that can display a multi-column layout uses animage that fits in one column, which might be smaller than an image used for asingle-column layout on a narrower screen.

Pixel density descriptor

You can also use descriptors to provide an alternate version of images toshow on high-density displays, to keep images looking sharp at the higherresolutions they provide.

Responsive images | web.dev (6)

Use the density descriptor to describe the pixel density of the image inrelation to the image in the src attribute. The density descriptor is a numberfollowed by the letter x, as in 1x or 2x.

<img src="small-image.png" alt="A description of the image." width="300" height="200" loading="lazy" decoding="async" srcset="small-image.png 1x, medium-image.png 2x, large-image.png 3x">

If small-image.png is 300 by 200 pixels in size, and medium-image.png is600 by 400 pixels, then medium-image.png can have 2x after it in thesrcset list.

You don't have to use whole numbers. If another version of the image is 450 by300 pixels in size, you can describe it with 1.5x.

Presentational images

Images in HTML are content. That's why you include the alt attributewith a description of the image for screen readers and search engines.

If you embed an image that's decorative, without any meaningfulcontent, you can use an empty alt attribute.

<img src="flourish.png" alt="" width="400" height="50">

You must always include the alt attribute, even if it's empty.An empty alt attribute tells a screen reader that the image ispresentational. A missing alt attribute doesn't provide that information.

Ideally, presentational or decorative images are included with CSS instead ofHTML. HTML is for structure. CSS is for presentation.

Background images

Use the background-image property in CSS to load presentational images.

element { background-image: url(flourish.png);}

You can specify multiple image candidates using theimage-setfunction for background-image.

The image-set function in CSS works a lot like the srcset attribute in HTML.Provide a list of images with a pixel density descriptor for each one.

element { background-image: image-set( small-image.png 1x, medium-image.png 2x, large-image.png 3x );}

The browser chooses the most appropriate image for the device's pixel density.

There are many factors to consider when you're adding images to your site,including:

  • Reserving the right space for each image.
  • Figuring out how many sizes you need.
  • Deciding whether the image is content or decorative.

It's worth spending the time to get your images right. Poor image strategies canannoy and frustrate your users. A good image strategy makes your site feelsnappy and sharp, regardless of the user's device or network connection.

There's one more HTML element in your toolkit to give you more control over yourimages: the picture element.

Check your understanding

Test your knowledge of images.

Styles must be added for images to fit within the viewport.

True

Images without containment will be as large as their natural size.

False

Styles are required.

When an image's height and width have been forced into an unnatural aspect ratio, which styles can help adjust how the image fits into these proportions?

object-fit

Specify how the image fits with keywords like contain and cover.

image-fit

This property doesn't exist, I made it up.

fit-image

This property doesn't exist, I made it up.

aspect-ratio

This may cause or solve an unnatural image ratio.

Putting height and width on your images prevents CSS from being able to style it differently.

True

Think of them more like hints than rules.

False

CSS has a large amount of dynamic options for sizing images, even if height and width are inline on the tag.

The srcset attribute doesn't _______ the src attribute, it _______ it.

complement, replaces

srcset definitely doesn't replace the src attribute.

replace, complements

It provides additional options for the browser to choose from, if it's capable.

Missing alt on an image is the same as an empty alt.

True

An empty alt attribute tells a screen reader that this image is presentational.

False

Missing alt signals nothing to a screen reader.

Responsive images  |  web.dev (2024)

FAQs

How do I fix responsive image test? ›

How do I fix it ? This issue can be fixed by using responsive images, which relies on creating multiple versions of each image, that are served via CSS media queries depending on the user's viewport dimensions. Another solution can be to use vector-based image formats like SVG.

Which image format is best for responsive website? ›

In short, when it comes to web design:
  • JPEG is great for colorful photos, keeping them small for fast website loading.
  • PNG is ideal for logos and graphics with transparency, maintaining clarity.
  • GIF adds life with simple animations, perfect for social media reactions and icons.
May 15, 2024

What is the best practice for responsive images? ›

Responsive images with plain CSS

Including the width and height values in the HTML is best practice. This ensures that the browser reserves the necessary space for the image and there's no subsequent page reflow as the image is loading. These values will override my HTML.

How do you make a website image responsive? ›

An image can be made responsive by using CSS and setting the width of the image to be a percentage of its parent container, rather than a fixed pixel value. This way, when the size of the parent container changes (e.g. due to different screen sizes), the size of the image will also change proportionally.

How to make an image responsive in HTML without CSS? ›

Add the <img> tag to your HTML and set the src attribute to point to the image location. Optionally, set the width and height attributes to define the image size. Always add an alt attribute to describe the image. Save the changes to your HTML file.

What is the best image format for web Dev? ›

So, which format should you use? WebP and AVIF will generally provide better compression than older formats, and should be used where possible. You can use WebP or AVIF images along with a JPEG or PNG image as a fallback.

Is WebP better than PNG? ›

WebP uses lossy and lossless compression, whereas PNG only supports lossless compression. This means WebP can achieve smaller file sizes without compromising image quality, making it an ideal choice for web use. PNG's lossless compression, on the other hand, results in higher-quality images but larger file sizes.

What is the best image size for responsive websites? ›

Generally recommended image sizes for websites
Website Image TypeImage Dimensions (W x H)Image Aspect Ratio
Background Image1920 x 1080 pixels16:9
Hero Image1280 x 720 pixels16:9
Website Banner250 x 250 pixels1:1
Blog Image1200 x 630 pixels3:2
6 more rows
Jul 8, 2024

Why should developers make images responsive? ›

By using responsive images, website developers can ensure that images are appropriately sized for the device they are being viewed on, resulting in a better user experience.

How do I get good at responsive design? ›

Responsive Design Best Practices
  1. Eliminate Friction. ...
  2. Design for Thumbs. ...
  3. Take Advantage of Mobile Devices' Native Hardware. ...
  4. Make Layouts Fluid/Adaptive by Default. ...
  5. Don't Forget About Landscape Orientation. ...
  6. Remember, Typography Can Be Responsive Too. ...
  7. Lazy Load Non-vital Images and Videos. ...
  8. Conditional Loading.

What are the responsive image techniques? ›

Responsive images are the set of techniques used to load the right image based on device resolution, orientation, screen size, network connection, and page layout. The browser should not stretch the image to fit the page layout, and loading it shouldn't result in time & bandwidth wastage.

How do I make my website completely responsive? ›

How to create a Responsive Website
  1. Set Appropriate Responsive Breakpoints. ...
  2. Start with a Fluid Grid. ...
  3. Take touchscreens into consideration. ...
  4. Define Typography. ...
  5. Use a pre-designed theme or layout to save time. ...
  6. Test Responsiveness on Real Devices.
Dec 8, 2022

How do I optimize an image for a website? ›

How to optimize images for the web
  1. Benchmark your current site speed.
  2. Know how to choose the best image file type.
  3. Resize your images before exporting.
  4. Compress images to reduce file size.
  5. Automate image optimization with a WordPress plugin.
  6. Use the “blur up” technique to load a Lower Quality Image first.
Jun 6, 2024

What is responsive design in UX design? ›

Responsive web design responds to user needs by adapting to different screen sizes, orientations, layouts, and platforms. This is accomplished with the use of flexible grids and layouts, responsive images, and CSS media queries.

How do I fix my screen responsiveness? ›

Here are the 11 ways to fix the phone screen not responding to touch.
  1. Restart Your Phone. ...
  2. Remove the Screen Protector or Case. ...
  3. Dry out Your Cell Phone. ...
  4. Upgrade Your Operating System. ...
  5. Optimize Device Performance. ...
  6. Adjust Touch Sensitivity. ...
  7. Turn Off Special Feature or Developer Mode. ...
  8. Turn On Safe Mode.

How do I fix my touch screen response? ›

How to Fix a Touch Screen That Isn't Working
  1. Restart the device. ...
  2. Clean the touch screen and screen protector. ...
  3. Dry off your smartphone. ...
  4. Gently tap each corner of the phone. ...
  5. Remove the SIM card, memory cards, and peripherals. ...
  6. Turn on Safe Mode for Android or Windows safe mode. ...
  7. Adjust iPhone 3D Touch sensitivity.

Top Articles
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 5476

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.