Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

place footer at bottom only if page is "short"

Tags:

html

jquery

css

i have a website with several pages. each page has different height (obvious, but i mention it).

what i would like to achieve is that if the content of the page is lower then the browser viewport, the footer tag will get a fixed position and will be aligned to the bottom of the page.

iv'e tried this js:

$(function(){
if ($(document).height() > $("footer").offset().top+44) {
        $("footer").addClass('fixbottom');
    }
}
});

$(window).resize(function() {
    if ($(document).height() > $("footer").offset().top+44) {
        $("footer").addClass('fixbottom');
    }
});

and that css:

.fixbottom {
    width: 100%;
    position: fixed;
    bottom: 0;
}


footer {
height:44px;
    background: #7abde9;
    color: #ffffff;
    text-align: center;
}

the top+44 in my jquery is because my footer tag is 44 height iv'e used the document ready and window resize to make sure all situations should meet, but unfortunately that's does not seem to work in any case.

any help should be greatly appriciated

like image 429
sd1sd1 Avatar asked Jan 18 '14 15:01

sd1sd1


2 Answers

I didn't like the idea of a big wrapper containing everything, so I found this solution:

html {
    position: relative;    /*IMPORTANT: otherwise the footer aligns to the :root, which is 100vh*/

    min-height: 100%;    /*if the page is "short", the html takes it up completely anyway*/
}
body {
    margin-bottom: 10rem;    /*this is the height of the footer (if it is not fixed you can find a way using media queries*/
}
footer {
    position: absolute;
    bottom: 0;

    height: 10rem;    /*set whatever you want, but remember to keep it synced with the body*/
}

The important thing to remember is that margin-bottom must be set on the body, since the footer it positioned inside the html tag which is its direct parent.


DISCLAIMER:

I found this solution on my own, but I didn't check whether someone else has found it out on any other questions... In that case, feel free to reference them in the comments!

like image 177
Simo Pelle Avatar answered Oct 12 '22 23:10

Simo Pelle


Possible solution in 2020: wrap the non-footer content in a tag and set the min-height of that tag to 100vh - the footer height:

HTML:

<main>
    <!--Page Content-->
</main>

<footer>
    <!--Footer Content-->
</footer>

CSS:

main {
    min-height: calc(100vh - <footer height>);
}

No JavaScript/jQuery needed.

like image 36
Louis Avatar answered Oct 12 '22 22:10

Louis