CSS Background Size
The background-size property in CSS allows you to control the size of the background image. It can be used to make the image fit the element, cover the area, or be displayed at specific dimensions.
Key Points on CSS Background Size:
- The
background-size
property accepts values such ascover
,contain
, or specific width and height values. background-size: cover
makes the background image cover the entire element, potentially cropping it.background-size: contain
ensures the entire image is visible within the element, maintaining its aspect ratio.- Specific width and height values can be set to resize the background image.
- The property can be set with two values:
background-size: width height;
for custom dimensions.
Syntax for CSS Background Size:
Syntax Example
/* Background size syntax */
background-size: cover | contain | width height;
/* Example */
background-size: cover;
Examples of CSS Background Size:
The following examples demonstrate the usage of the background-size
property:
Code Example: Background Size Cover
div {
background-image: url('https://tse2.mm.bing.net/th?id=OIP.BOTVdTKoxYQceN_idpCWSwHaFi&pid=Api&P=0&h=220');
background-size: cover;
}
Output
This div has a background image set to cover.
Code Example: Background Size Contain
div {
background-image: url('https://tse2.mm.bing.net/th?id=OIP.BOTVdTKoxYQceN_idpCWSwHaFi&pid=Api&P=0&h=220');
background-size: contain;
}
Output
This div has a background image set to contain.
Code Example: Custom Background Size
div {
background-image: url('https://tse2.mm.bing.net/th?id=OIP.BOTVdTKoxYQceN_idpCWSwHaFi&pid=Api&P=0&h=220');
background-size: 50% 50%;
}
Output
This div has a background image with custom size.
Common Background Size Values:
- cover: Ensures the background image covers the entire element area, potentially cropping parts of the image.
- contain: Ensures the entire image is visible within the element, adjusting the size while maintaining the aspect ratio.
- width height: Sets custom width and height values for the background image. Can be in any valid CSS unit (e.g., px, %, em).
When using background-size, it's important to consider the aspect ratio of the image and how it will be displayed within the element. Both cover
and contain
are helpful in different scenarios depending on whether you want to fill the element or ensure the full image is visible.