CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

前端 未结 29 2484
悲哀的现实
悲哀的现实 2020-11-21 23:48

I have the following page (deadlink: http://www.workingstorage.com/Sample.htm ) that has a footer which I can\'t make sit at the bottom of the page.

I wa

29条回答
  •  难免孤独
    2020-11-22 00:26

    Dynamic one liner using jQuery

    All CSS methods I have come across are too rigid. Also, setting the footer to fixed is not an option if that's not part of the design.


    Tested on:

    • Chrome: 60
    • FF: 54
    • IE: 11

    Assuming this layout:

    
    
    
      

    Use the following jQuery function:

    $('#content').css("min-height", $(window).height() - $("#footer").height() + "px");
    

    What that does is set the min-height for #content to the window height - the height of the footer what ever that might be at the time.

    Since we used min-height, if #content height exceeds the window height, the function degrades gracefully and does not any effect anything since it's not needed.

    See it in action:

    $("#fix").click(function() {
      $('#content').css("min-height", $(window).height() - $("#footer").height() + "px");
    });
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    html {
      background: #111;
    }
    
    body {
      text-align: center;
      background: #444
    }
    
    #content {
      background: #999;
    }
    
    #footer {
      background: #777;
      width: 100%;
    }
    
    
    
    
    
      

    Very short content

    Same snippet on JsFiddle


    Bonus:

    We can take this further and make this function adapt to dynamic viewer height resizing like so:

    $(window).resize(function() {
        $('#content').css("min-height", $(window).height() - $("#footer").height() + "px");
      }).resize();
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    html {
      background: #111;
    }
    
    body {
      text-align: center;
      background: #444
    }
    
    #content {
      background: #999;
    }
    
    #footer {
      background: #777;
      width: 100%;
    }
    
    
    
    
    
      

    Very short content

提交回复
热议问题