OneBite.Dev - Coding blog in a bite size

make background image fit screen css

Code snippet for how to make background image fit screen css with sample and detail explanation

Having a visually appealing background is an important part of a website’s design. In this article, we’re going to discuss about how to make a background image fit the screen using CSS.

Code snippet for Background Image Fit Screen

To ensure your background image completely covers the entire screen, regardless of the device or screen size your website visitors are using, you can take advantage of the CSS background-size property. Below is a simple CSS code snippet:

body {
    background-image: url('image.jpg');
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
    height: 100vh;
}

Code Explanation for Background Image Fit Screen

Let’s break down this CSS code we used to make a background image visually fill the screen:

  1. background-image: url('image.jpg');: This line of CSS code sets the background image of the webpage. You have to replace 'image.jpg' with the image you wish to set as the background. If your image is in another directory, ensure you give the correct path.

  2. background-size: cover;: The background-size property is set to cover so that your background image covers the entire container. Cover scales the background image as large as possible so that it completely covers the background area. It may also mean that parts of your background image may not be in view within the background positioning area

  3. background-repeat: no-repeat; : This ensures the image does not repeat itself across the container. It will only display once.

  4. background-position: center center;: This property positions the background image. The first value is the horizontal position and the second value is the vertical. Setting both to center ensures the background image remains at the center of the container both vertically and horizontally.

  5. height: 100vh;: This sets the height of the container. vh stands for viewport height. Therefore 100vh is 100% of the viewport’s height. Thus, the container (and so the image) will always stretch to the full height of the window.

Remember, CSS is quite flexible. You can adjust these properties as necessary to achieve the desired design and responsiveness for your website.

css