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:
-
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. -
background-size: cover;
: Thebackground-size
property is set tocover
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 -
background-repeat: no-repeat;
: This ensures the image does not repeat itself across the container. It will only display once. -
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 tocenter
ensures the background image remains at the center of the container both vertically and horizontally. -
height: 100vh;
: This sets the height of the container.vh
stands for viewport height. Therefore100vh
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.