Keeping HTML footer at the bottom of the window if page is short

こ雲淡風輕ζ 提交于 2019-11-28 09:13:28

Check out this site. He has a good tutorial on how to do this with css.

I copied his css just in case Matthew's site is taken down.

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
#container {
   min-height:100%;
   position:relative;
}
#header {
   background:#ff0;
   padding:10px;
}
#body {
   padding:10px;
   padding-bottom:60px;   /* Height of the footer */
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;   /* Height of the footer */
   background:#6cf;
}

EDIT

Since the height of the footer is different from page to page, you could get the height of the footer and then adjust the #body padding-bottom with javascript. Here is an example using jquery.

$(function(){
    $('#body').css('padding-bottom', $('#footer').height()+'px');   
});  

Give this a try.

It is a copy of the styles that Github uses to keep it's footer at the bottom of a page. It is a little hacky, and requires you to know the height of your footer (which may not work for your use case)

Markup


<div class="wrapper">
<div class="content"><p>Page Content</p></div>
<div class="footer-push"></div>
</div>

<footer>
  <p>footer-text</p>
  <img src="http://placekitten.com/100/100" alt="footer image">
</footer>

CSS (well, scss)


// our page element

html {
height:100%;
}

body {
height:100%;
}
.wrapper {
background:gray;
min-height:100%;
height: auto !important; // the magic!
height:100%;
margin-bottom:-158px; // the height of our footer + margin
}

.footer-push {
clear:both;
height:158px; // the height of our footer + margin
}

footer {
background:rgba(#a388a3,0.8);
margin-top:20px;
height:138px;
}

The important things here seem to be:

  • Setting height: 100% on containing elements (esp html and body)
  • Knowing the height of your footer, and accounting for it with a "push" element
  • using the combination of min-height height: auto !important and height:100%

Hope that helps!

HTML

<body>
    <div class="example">
        <p>Lorem ipsum dolor sit amet consectetur...</p>
    </div>

    <footer>
        <ul>
            <li>One</li>
            <li>Two</li>
            <li>Three</li>
        </ul>
    </footer>
</body>

CSS

body {
    min-height: 100%;
}

footer {
    position: absolute;
    bottom: 0;
}

Considering that all your footer is inside the <footer> html tag, this is an easy solution using jQuery.

JS:

$(document).ready(function(){
    $('body').css('padding-bottom', $('footer').height()+'px');
});

CSS:

footer {
    position:absolute;
    bottom:0;
}

No it's very easy set a minimum for your body height.

like this: min-height:500px; then the min height is 500px.

use min-height property, though not entirely reliable as some older versions may not support it. Throw in some javascript if you dont mind.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!