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%.
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%.
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:
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.
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:
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.