How to properly set the 100% DIV height to match document/window height?

前端 未结 9 1828
难免孤独
难免孤独 2021-01-30 04:53

I have a wrapper positioned to center with an y-repeated background image:


    
...some content
&
9条回答
  •  孤独总比滥情好
    2021-01-30 05:17

    I figured it out myself with the help of someone's answer. But he deleted it for some reason.

    Here's the solution:

    1. remove all CSS height hacks and 100% heights
    2. Use 2 nested wrappers, one in another, e.g. #wrapper and #truecontent
    3. Get the height of a browser viewport. IF it's larger than #wrapper, then set inline CSS for #wrapper to match the current browser viewport height (while keeping #truecontent intact)
    4. Listen on (window).resize event and ONLY apply inline CSS height IF the viewport is larger than the height of #truecontent, otherwise keep intact

      $(function(){
          var windowH = $(window).height();
          var wrapperH = $('#wrapper').height();
          if(windowH > wrapperH) {                            
              $('#wrapper').css({'height':($(window).height())+'px'});
          }                                                                               
          $(window).resize(function(){
              var windowH = $(window).height();
              var wrapperH = $('#wrapper').height();
              var differenceH = windowH - wrapperH;
              var newH = wrapperH + differenceH;
              var truecontentH = $('#truecontent').height();
              if(windowH > truecontentH) {
                  $('#wrapper').css('height', (newH)+'px');
              }
      
          })          
      });
      

提交回复
热议问题