0

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?

Community
  • 1
  • 1
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87

2 Answers2

1

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).

Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
0

This might help:

position: fixed;
background-position: center;
overflow-x: hidden;
width: 100%;
height: 100%;
background: url(img/xxx.jpg);
background-size: 100%;
background-attachment: fixed;
overflow-y: scroll;
Ahmad Baktash Hayeri
  • 5,802
  • 4
  • 30
  • 43
WoShiNiBaBa
  • 257
  • 5
  • 19