Make a sticky footer
Mar 10, 2016 · 1 分钟阅读

Our html

<body>
  <main></main>
  <footer></footer>
</dody>

Use CSS

html { position: relative; min-height: 100%;}
body { margin-bottom: 50px;}
footer { position: absolute; left: 0; right: 0; bottom: 0; height: 50px;}

with calc():

main { min-height: calc(100vh - 50px);}
footer { height: 50px;}

with flexbox:

html { height: 100%;}
body { min-height: 100%; display: flex; flex-direction: column;}
main { flex: 1;}

with grid:

html { height: 100%;}
body { min-height: 100%; display: grid; grid-template-rows: 1fr auto;}
footer { grid-row: 2 / 3;}

Use JavaScript

function activateStickyFooter(selector) {
  function adjustFooterCssTopToSticky() {
    // remember to set the position of the footer as relative
    const footer = document.querySelector(selector);
    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);
  }

  adjustFooterCssTopToSticky()
  window.addEventListener('resize', adjustFooterCssTopToSticky);
}
← Previous Post Next Post →

Ryun的博客
与其感慨路难行,不如马上出发。

atom css design git html javascript jekyll laravel life mac mobile optimization sublime tool vscode vue
mac

About

你好,❤朋友

这里是 Ryun 的博客 📝

📝记录了我学习 🔎的过程

作为一名前端攻城狮 🦁

希望能和大家一起 🔎

共同进步 🏃

🦁的特长:

  • HTML5
  • CSS3
  • JavaScript
  • Vue.js
  • 微信小程序
  • 熟练配合 Node.js、PHP 和 Laravel
  • 熟练使用各种开发和设计工具

🦁喜欢 🆒🆒的东西

对提升效率和美感的事物有兴趣 😋

欢迎 👏交流


see this hugo-theme-dream-ink