I just wrote an article about this. You can find it on medium.
There are tons of CSS valid solutions, but I recommend using Javascript to achieve this result.
The main idea behind this is that you want to know what the height above the footer is and what how much you need to adjust the footer's top in order to move it to the bottom. Here's a Gist that does exactly that.
Here's code that does it (assuming you footer is the order with id #footer
):
window.addEventListener("load", activateStickyFooter);
function activateStickyFooter() {
adjustFooterCssTopToSticky();
window.addEventListener("resize", adjustFooterCssTopToSticky);
}
function adjustFooterCssTopToSticky() {
const footer = document.querySelector("#footer");
const bounding_box = footer.getBoundingClientRect();
const footer_height = bounding_box.height;
const window_height = window.innerHeight;
const above_footer_height = bounding_box.top - getCssTopAttribute(footer);
if (above_footer_height + footer_height <= window_height) {
const new_footer_top = window_height - (above_footer_height + footer_height);
footer.style.top = new_footer_top + "px";
} else if (above_footer_height + footer_height > window_height) {
footer.style.top = null;
}
}
function getCssTopAttribute(htmlElement) {
const top_string = htmlElement.style.top;
if (top_string === null || top_string.length === 0) {
return 0;
}
const extracted_top_pixels = top_string.substring(0, top_string.length - 2);
return parseFloat(extracted_top_pixels);
}
If you want a more detailed answer, head over to the medium article. I also wrote a JS Fiddle for this.