Specifying the width for scaling

Example1

img {
width: 100%;
height: auto;
}

CSS images sizes change in response to different dimensions of the browser window. You need to set either width or max-width properties for CSS to respond to such changes.

You can enable scaling down and up by setting the width to 100%.

2200 x 600

800 x 800

Specifying the width for scaling

Example2

img {
max-width: 100%;
height: auto;
}

In the example above, the image can be scaled up until it becomes larger than the original size. Therefore, images might have poorer quality on bigger screens.

To prevent responsive images from becoming bigger than their original CSS image sizes, use max-width, and set it to 100%.

2200 x 600

800 x 800

Setting background-size to fit screen

Example3

html {
background: url(‘image.png’) no-repeat center fixed;
background-size: cover;
}

Using CSS, you can set the background-size property for the image to fit the screen (viewport).

The background-size property has a value of cover. It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.

In this code example, we make the CSS background image size fit the screen:

  • The responsive background image fills the whole page without leaving whitespace.
  • The image is at the center, scales if necessary, and does not require a scroll bar.

2200 x 600

800 x 800

Keeping the aspect ratio

Example4

div {
width: 100%;
height: 300px;
background-image: url(‘doggo.jpg’);
background-repeat: no-repeat;
background-size: contain;
border: 2px solid #e9385a;
}

Choose this method if you have a small image and want to keep its quality.

Set the background-size property to contain. It tells the browser that the background image scales trying to fit the content area, but does not lose its aspect ratio or get blurry.

2200 x 600

800 x 800

Stretching images to fill the area

Example5

div {
width: 100%;
height: 300px;
background-image: url(‘doggo.jpg’);
background-size: 100% 100%;
border: 2px solid #e9385a;
}

You can set the background-size property to 100% 100% to make the image stretch to fit a specific area:

2200 x 600

800 x 800

Covering the area, but keeping the aspect ratio

Example6

div {
width: 100%;
height: 300px;
background-image: url(‘doggo.jpg’);
background-size: cover;
border: 2px solid #e3985a;
}

To cover the area with the background image and keep its aspect ratio, you can set the background-size property to cover. It may cut off a part of the image to keep it proportional.

2200 x 600

800 x 800