简体   繁体   中英

Sticky footer to bottom when body height 100%

I like to create my styles based on the height of the window and typically do that by creating html and body to be height 100%

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

Then I can style the heights of remaining elements based on that as shown in the jsfiddle below. Problem is, I want my footer to stick to the bottom which works great for pages that don't go beyond the window height, but if they do the footer is fixed there. How can I fix it such that I still use the html,body height of 100% and still get the footer to stick to bottom always. *Note: I have done the wrapper way of

#wrapper{
  min-height:100%;
}

and that didn't work too well cause the children elements' height doesn't work well.

http://jsfiddle.net/mmahalwy/m4AjL/

Suggestions?


Edit: Got it solved this way: http://jsfiddle.net/mmahalwy/7wqqF/

Thanks everyone!

Here is the problem ,

You are using 2 css styles tag of 100% height each named class=block if you just made a main div with a height of 100% and all other div inside it everything will work fine .

<body>
    <container>
        <div class="block">
             <h1>Content</h1>

        </div>
        <div class="block">
             <h1>Content</h1>

        </div>
    </container>
    <footer>I am a footer</footer>
</body>

html, body {
    min-height: 100%;
    height: 100%;
}
container {
    background: grey;
    display: block;
    height: 100%;
    width: 100%;
}
.block {
    height: auto;
}
footer {
    background-color: blue;
    color: white;
    position: relative;
    bottom: 0px;
    width: 100%;
}

The best answer might depend on what type of browser compatibility you need.

IMHO, the modern way to accomplish this is to use CSS3 flexbox, see this useful guide from css-tricks.com .

The code is in this JSFiddle: http://jsfiddle.net/m4AjL/24/ .

HTML:

<body>
    <div class="container">
        <div class="block">
            <h1>Content</h1>
        </div>
        <div class="block">
            <h1>Content</h1>
        </div>
    <footer>I am a footer</footer>
    </div>
</body>

CSS:

html, body{
    min-height: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}
body{
    display: flex;
    flex-direction: column;
}
.block{
    display: block;
    height: 100%;
}
footer{
    background-color: blue;
    color: white;
    width: 100%;
    flex: none;
}
.container{
    flex: 1;
    overflow-y: auto;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM