Languages
[Edit]
EN

HTML / CSS - how to create responsive image?

6 points
Created by:
Sujay
272

In this article, we would like to show you how to create a responsive image using HTML and CSS.

As a responsive image, we understand the image that is matched to desired device size. It is good to provide good image quality, so srcset attribute should be used to let the browser load proper image size depending on device width. When srcset attribute is not supported, older browsers ignore it using src attribute.

HTML / CSS - how to create responsive image?
Responsive image with pure HTML and CSS.

Note:  above animation presents Google Chrome DevTools, when browser window size is changed (look on loaded images on the right list on window resize).

 

Practical example

In this example, we set the CSS width property to 100% and height to auto to create a responsive image. Optionally you can use max-width style property if you don't want your image to be larger than indicated size. According to current window size, browser selects and loads the best image to provide good image quality.

Runnable example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

	.responsive-image {
		width: 100%;
		height: auto;
		max-width: 800px;
	}

  </style>
</head>
<body>
  <img class="responsive-image"
       src="https://dirask.com/static/bucket/1624644642515-akQVVd9QRn--example-img-429w.jpg" 
       srcset="https://dirask.com/static/bucket/1624644642515-akQVVd9QRn--example-img-429w.jpg 429w,
               https://dirask.com/static/bucket/1624644642578-6pQmx29Ab5--example-img-600w.jpg 600w,
               https://dirask.com/static/bucket/1624644642609-mbQLqBEYJX--example-img-730w.jpg 730w" 
  />
</body>
</html>

Note:

Copy source code to your local file, open it and resize your browser window to see the effect.

Used resources:

HTML / CSS - responsive image example-img-429w.jpg
HTML / CSS - responsive image example-img-429w.jpg
HTML / CSS - responsive image example-img-600w.jpg
HTML / CSS - responsive image example-img-600w.jpg
HTML / CSS - responsive image example-img-730w.jpg
HTML / CSS - responsive image example-img-730w.jpg

References

  1. Responsive images - MDN Docs
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join