zaro

How to make a background image show only once in CSS?

Published in CSS Styling 2 mins read

To prevent a background image from repeating and display it only once, use the background-repeat property in CSS and set its value to no-repeat.

Here's a detailed explanation:

The background-repeat property controls how a background image is repeated (tiled) on an element. By default, background images repeat both vertically and horizontally to cover the entire element. Setting background-repeat: no-repeat; ensures the image appears only once, in its original size and position.

Here's how you can implement it:

body {
  background-image: url("your-image.jpg"); /* Replace with your image URL */
  background-repeat: no-repeat;
}

Explanation:

  • background-image: url("your-image.jpg");: This line sets the background image for the body element. Replace "your-image.jpg" with the actual URL of your image.
  • background-repeat: no-repeat;: This line is the key. It tells the browser not to repeat the background image. It will be displayed only once.

Further Considerations and related properties:

While background-repeat: no-repeat; stops the repetition, you might also want to control:

  • background-position: Determines where the single image is placed within the element. Common values include center, top left, bottom right, or specific coordinates like 10px 20px.

    background-position: center; /* Centers the image */
  • background-size: Controls the size of the background image. Useful values include:

    • cover: Scales the image to cover the entire element, potentially cropping parts of the image.
    • contain: Scales the image to fit within the element, maintaining its aspect ratio, which might leave some empty space.
    • auto: The browser will scale the image to its natural size, while maintaining its aspect ratio.
    • Specific dimensions (e.g., 200px 100px): Sets the width and height of the image explicitly.
    background-size: cover; /* Scales to cover the element */

Example combining properties:

body {
  background-image: url("your-image.jpg");
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}

This example sets the background image to display only once, centers it within the body element, and scales it to cover the entire element.