Search code examples
jquerycssbackground-size

background-size: cover; property


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


Solution

  • 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);