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:

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:

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.