1

My page is long and requires the user to scroll to view the entire thing. I want the background (it's a CSS3 gradient) to stretch throughout the entire length of the page, even if the user resizes the window. I am using a bit of code from another thread that does this. However once I switch the page to fullscreen the background is cut off at the bottom. The code I am using is below.

function adjustBackground() {
    var pageHeight = $('html').height();
    var body = document.body,
        html = document.documentElement;

    var height = Math.max( body.scrollHeight, body.offsetHeight, 
                           html.clientHeight, html.scrollHeight, html.offsetHeight );
    document.getElementById("page-top").style.backgroundSize = "100% " + height + "px";
}
/* 
  page-top is the ID of the body. 
  The code gets the height of the page and should 
  set the height of the page to the height.
*/

$(document).ready(function(){
   adjustBackground();
});

body.onresize=function(){
    adjustBackground();
};
strah
  • 6,702
  • 4
  • 33
  • 45
judgebeanhead
  • 31
  • 1
  • 1
  • 3
  • if the background is a CSS gradient, you shouldn't have to set any size for it - it should fill the whole container by default (?) – Johannes May 04 '16 at 22:46
  • why use an id for the body if you've the reference to it already? – Montagist May 04 '16 at 22:49
  • Possible duplicate of [Making gradient background fill page with css](http://stackoverflow.com/questions/16841323/making-gradient-background-fill-page-with-css) – blurfus May 04 '16 at 22:54

2 Answers2

1

Try setting the min-height of both the body and html elements to 100%. What happens is the body doesn't actually extend all the way to the bottom of the viewport, so the background doesn't extend down there either (only 100% of the height of the body or html tag (if you set the background w/CSS).

You should be able to do this without any JavaScript (nicer for you to work with). Example:

body, html {
    min-height: 100%;
}

body {
    background: #ccc; /* Replace "#ccc" with your css gradient */
    background-size: 100% 100%;
}

You can use an online tool such as http://www.colorzilla.com/gradient-editor/ to generate the CSS you want for the gradient, if you want something visual.

timehat
  • 135
  • 6
  • Example JS Fiddle: https://jsfiddle.net/qtdgem42/ Remove the min-height: 100% on the html, body tags to see how crucial that is. – timehat May 04 '16 at 22:48
  • And, on second look, it appears you only need to set that on the html element. Perhaps non-Chrome browsers need it on both... I forget. :) – timehat May 04 '16 at 22:49
0

You can also try setting the body to span the whole page with the desired background using vw(hundredths of the viewport width) and vh(hundredths of the viewport height) from CSS3

body {
    background: #ccc; /* Replace "#ccc" with your css gradient */
    height: 100vh;
    width: 100vw;
}
Sitian Liu
  • 1,156
  • 10
  • 14