Background Position and Size

Background images are an important part of web design. CSS provides powerful properties to control how background images are placed and scaled. The two main properties used are background-position and background-size.

Background Position

The background-position property defines where the background image appears within an element. By default, the image is placed at the top left corner.

You can use keywords such as top, bottom, left, right, and center to control the position.

Example
background-position: center;

This places the image in the center of the element.

You can also combine values.

Example
background-position: top right;

This moves the image to the top right corner.

It is also possible to use pixel or percentage values.

Example
background-position: 50% 50%;

This centers the image both horizontally and vertically.

Example
background-position: 20px 30px;

This moves the image 20 pixels from the left and 30 pixels from the top.

Background Size

The background-size property controls the size of the background image.

You can set exact values.

Example
background-size: 200px 150px;

This sets the width to 200 pixels and height to 150 pixels.

You can also use percentages.

Example
background-size: 100% 100%;

This stretches the image to fill the entire element.

There are also special values.

The cover value scales the image to completely cover the element while maintaining aspect ratio. Some parts of the image may be cropped.

Example
background-size: cover;

The contain value scales the image so that it fits inside the element without cropping. Empty space may remain.

Example
background-size: contain;

Combining Position and Size

You can use both properties together to create better layouts.

Example
background-position: center;
background-size: cover;

This combination is commonly used for full-width banners and hero sections.

Best Practices

Use cover for full background sections such as headers or banners.

Use contain when you want the entire image to be visible.

Avoid stretching images too much as it can reduce quality.

Use high-quality images for better visual results.

Conclusion

Understanding background-position and background-size helps you control how images appear on your website. These properties allow you to create responsive and visually appealing designs with ease.