askvity

How to Make Background Image Fit Screen in CSS?

Published in CSS Background 3 mins read

To make a background image fit the entire screen in CSS, you can use the background-size property.

Here's how:

Using background-size: cover;

The most common approach is to use background-size: cover;. This ensures that the background image covers the entire container, which can be the screen (viewport) or any other element.

  • Pros:
    • The image will always fill the container, no matter its size.
    • The image maintains its aspect ratio, preventing distortion.
    • Some parts of the image may be clipped (cropped) if its aspect ratio doesn’t match the container.
  • Cons:
    • Parts of the image might not be visible if the aspect ratio of the image is different from the container.
body {
  background-image: url("your-image.jpg");
  background-size: cover;
  background-repeat: no-repeat; /* Prevent image from repeating */
}

Using background-size: contain;

Alternatively, you can use background-size: contain;. This will scale the image to fit inside the container without cropping.

  • Pros:
    • The entire image is always visible.
  • Cons:
    • May result in empty spaces within the container if the aspect ratio of the image and the container are significantly different.
body {
  background-image: url("your-image.jpg");
  background-size: contain;
  background-repeat: no-repeat; /* Prevent image from repeating */
}

Using background-size: 100vw 100vh;

As indicated in the reference, another method is to use background-size: 100vw 100vh;. This will stretch the background image to match the full width (100vw) and full height (100vh) of the viewport. This is equivalent to setting the width to be 100% of the viewport width and height to be 100% of the viewport height. This stretches the image to cover the entire viewport, adjusting the image's dimensions with the changing viewport size.

  • Pros:
    • The image will stretch to cover the entire screen
  • Cons:
    • The image may appear distorted if its aspect ratio does not match the viewport's aspect ratio.
body {
  background-image: url("your-image.jpg");
  background-size: 100vw 100vh;
  background-repeat: no-repeat; /* Prevent image from repeating */
}

Additional properties

  • background-repeat: no-repeat;: This prevents the background image from repeating itself across the screen.
  • background-position: center;: This property can be used in conjunction with background-size to center the image on the screen.

By combining these properties effectively, you can ensure your background image fits the screen as intended.

Related Articles