Search code examples
cssbackground-image

Resizable background-image in css body but avoid repeating


I am trying to add this image https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Coffee_and_Friends_(Unsplash).jpg/2560px-Coffee_and_Friends_(Unsplash).jpg as background-image for body selector.

Here's my code

body {
    background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Coffee_and_Friends_%28Unsplash%29.jpg/2560px-Coffee_and_Friends_%28Unsplash%29.jpg");
    background-size: cover;
    background-repeat: no-repeat;
}

it's working fine but at certain size image started to repeat so I added background-repeat: no-repeat; in code.

Now in place of repeated image there is white space in window, How to fill this white space with single image ?


Solution

  • Just add the background-position and background-attachment properties:

    • background-position will set the starting position of your background image
    • background-attachment (set to fixed) will prevent your background image from scrolling with the content of your page

    body {
        background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Coffee_and_Friends_%28Unsplash%29.jpg/2560px-Coffee_and_Friends_%28Unsplash%29.jpg");
        background-size: cover;
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-position: center;
    }
    
    p {
        font-size: 36px;
        font-family: sans-serif;
        color: #fff;
        text-align: center;
    }
    <body>
      <p>
        Some text
      </p>
    </body>