CSS Background-size
This CSS property is used to set the size of a background image of an element. It has two possible keyword values that contain and cover.
Syntax:
background-size: auto | length | cover | contain | initial | inherit;
Property Values:
auto: Displays the background image in its original size.
length: It is set the width and height of the background image.
percentage: The width and height of the background image to the percentage (%) of the background-positioning area.
cover: The background image to cover the entire container.
contain: It resizes the background image
initial: Its default value.
inherit: Its parent element.
Example: Auto
<!DOCTYPE html> <html> <head> <title> background-size property </title> <style> div { width: 300px; height: 200px; border: 2px solid red; } #div1{ background-image: url('lion.png'); background-size: auto; } #div2{ background-image: url('lion.png'); background-size: 150px 150px; } #div3{ background-image: url('lion.png'); background-size: 30%; } </style> </head> <body> <h2> background-size: auto; </h2> <div id = "div1"></div> <h2> background-size: 150px 150px; </h2> <div id = "div2"></div> <h2> background-size: 30%; </h2> <div id = "div3"></div> </body> </html>
OUTPUT:
Example:
We are using the cover, contain, and initial values.
<!DOCTYPE html> <html> <head> <title> background-size property </title> <style> div { width: 300px; height: 250px; border: 2px solid red; background-repeat: no-repeat; } #div1{ background-image: url('lion.png'); background-size: contain; } #div2{ background-image: url('lion.png'); background-size: cover; } #div3{ background-image: url('lion.png'); background-size: initial; } </style> </head> <body> <h2> background-size: contain; </h2> <div id = "div1"></div> <h2> background-size: cover; </h2> <div id = "div2"></div> <h2> background-size: initial; </h2> <div id = "div3"></div> </body> </html>
OUTPUT:
Example – Combining multiple images:
<!DOCTYPE html> <html> <head> <title> background-size property </title> <style> div { width: 250px; height: 250px; border: 2px solid red; background-repeat: no-repeat; background-position: center; } #div1{ background-image: url('lion.png'), url('forest.jpg'); background-size: 300px 150px, cover; } #div2{ background-image: url('lion.png'), url('forest.jpg'); background-size: 200px 150px, 300px 200px; } #div3{ background-image: url('lion.png'), url('forest.jpg'); background-size: 150px 175px, contain; } </style> </head> <body> <h2> background-size: 300px 150px, cover; </h2> <div id = "div1"></div> <h2> background-size: 200px 150px, 300px 200px; </h2> <div id = "div2"></div> <h2> background-size: 150px 175px, contain; </h2> <div id = "div3"></div> </body> </html>
OUTPUT: