Richard Hamilton Richard Hamilton - 5 months ago 10
CSS Question

Very weird behavior when working with background size CSS3

I recently learned about the

background-size
property thanks to this topic

Set size on background image with CSS?

As you can guess, I am trying to make a background image take up the full screen and no more/no less. Here is my fiddle

https://jsfiddle.net/1x7ytdaa/

document.body.style.backgroundImage = "url('http://www.crystalinks.com/ColosseumNight2.jpg')";
document.body.style.backgroundSize = "contain";


Here is what the
contain
property does


Scale the image to the largest size such that both its width and its height can fit inside the content area


It shouldn't matter what size the image is. If it's smaller, it should be scaled to the full size of the screen. If it's larger, it should be scaled down.

In the fiddle, you can see that the image is repeated 5 times horizontally and 5 1/2 times vertically.

I've tried
100% 100%
and while the width stretches the full screen, it still shows the same image 5 1/2 times vertically

I can not explain this behavior. Does anyone have any ideas?

Answer

Two things:

  • background-repeat
  • width and height of body

As you can in an edited fiddle, the problem is that the default value of background-repeat is repeat. Therefore, the image will be repeated rather than stretched. That doesn't solve everything, though, as the body and HTML elements should have a width defined that is 100%.

html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

document.body.style.backgroundImage = "url('http://www.crystalinks.com/ColosseumNight2.jpg')";
document.body.style.backgroundSize = "contain";
document.body.style.backgroundRepeat = "no-repeat";

If you want to cover the whole screen, use cover instead of contain. Cover makes sure that the element is completely covered, whereas contain simply makes sure that the background image is maximally contained (which can cause white space).