0

Whenever the background image changes, I need it to cover the body. I'm using background-size: cover, but it doesn't seem to work.

body {
   position: relative;
   margin-top: 60px;
   background-color: #000;
   font-family: 'Roboto Slab', serif;
   background: url(https://i.ytimg.com/vi/lECC6eQhnZo/maxresdefault.jpg); 
   background-repeat: no-repeat;
   background-position: center center;
   background-atachment: fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
   transition: background 1s;

and here's the jQuery that changes the image:

$("body").css("background", objects[newNum].img);

the images are stored in an array (objects).

CodePen: http://codepen.io/Chantun/pen/WxXaGy?editors=0010

TylerH
  • 20,799
  • 66
  • 75
  • 101
Chantun
  • 81
  • 1
  • 7

4 Answers4

1

background cover is right work. on default body height: auto. use min-height: 100vh for body. and change margin-top to padding-top.

body {
  min-height: 100vh;
  padding-top: 60px;
}

Codepen

Andrei Fedorov
  • 3,689
  • 2
  • 13
  • 25
1

Changing background-attachment on your codepen to have two t's instead of one does make it work how I think you want it. You can also combine your background rules into shorthand like:

background: #000 url(https://i.ytimg.com/vi/lECC6eQhnZo/maxresdefault.jpg) center center / cover no-repeat;
background-attachment: fixed;
miken32
  • 42,008
  • 16
  • 111
  • 154
Ben Rhys-Lewis
  • 3,118
  • 8
  • 34
  • 45
0

You need to change your usages of background to background-image. Because it conflicts with background-size.

So for your CSS it would be:

body {
   position: relative;
   margin-top: 60px;
   background-color: #000;
   font-family: 'Roboto Slab', serif;
   background-image: url(https://i.ytimg.com/vi/lECC6eQhnZo/maxresdefault.jpg); 
   background-repeat: no-repeat;
   background-position: center center;
   background-atachment: fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
   transition: background 1s;

And for your JS it should be:

$("body").css("background-image", objects[newNum].img);
Ubie
  • 26
  • 2
0

Just a heads up!

background-attachment: fixed and background-size: cover don't play nicely with each other! :(

More detailed explanation about how and why they clash here: https://stackoverflow.com/a/23811091

Edit: also your background-attachment: fixed is misspelled! :)

Community
  • 1
  • 1