OneBite.Dev - Coding blog in a bite size

center background image in css

Code snippet for how to center background image in css with sample and detail explanation

A background image can become a powerful element in web design, establishing visual interest and reinforcing your brand identity. In CSS, you can harness numerous tricks to manage your background images, and centering them is one common technique you might need.

CSS Code Snippet for Centering a Background Image

Here is an example of how you can center a background image in CSS:

body {
    background-image: url('image.jpg');
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: cover;
    height: 100%;
    overflow: hidden;
    padding: 0;
    margin: 0;
}

Code Explanation for CSS Code Snippet

In the code snippet above:

  • background-image: url('image.jpg'); This line sets the image you want to use as a background. You just need to replace 'image.jpg' with the path to your image file.

  • background-position: center center; This line centers your image both vertically and horizontally in the container. The first value is for the horizontal position and the second for the vertical position.

  • background-repeat: no-repeat; This line prevents the image from repeating itself in case the image is smaller than the container.

  • background-attachment: fixed; This line makes the background image stay in place when you scroll through the webpage.

  • background-size: cover; This line automatically resizes the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges.

  • height: 100%; This line ensures the container for your background image (in this case, the body of your web page) is always at full height.

  • overflow: hidden; This line prevents scrollbars from appearing in case the content is bigger than its container.

  • padding: 0; and margin: 0; These lines remove any default padding and margin, making the background image cover the entire body without any spaces.

By understanding and appropriately using these elements, you can expertly control your background image positioning in CSS.

css