Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to make my footer "sticky" but the heights vary so can't use most of the methods I've found or flexbox. Is there any way to check with javascript how much space is under a div so I can add that much margin?

The html looks like this:

  <container>
     <header></header>
     <body><sometimes sub content></sub content></body>
     <footer></footer>
   </container> 

Also tried putting the footer outside of the container, saw that in some solutions, but again they all require a fixed height.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
136 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can check if $(document).height() > $(window).height(). That will tell you if the height of the content is longer than the viewport. If so, leave the footer where it is. If the doc height is <= the viewport height, add make the footer sticky. Like so:

To see the difference between sticky and non-sticky, run the snippet below to have the footer at the bottom of the page. To view it where the footer is sticky, run the snippet in full screen mode (on the top right corner of the snippet output). You can also just run it in full screen mode and then shrink your browser size down - it recalculates on window resize.

$(window).on("load resize", function() {
  // if content height <= viewport height, make footer sticky
  // else leave footer at the bottom of the content. 
  $(".footer").toggleClass("sticky", $(document).height() <= $(window).height());
});
.footer {
  width: 100%;
  background-color: #555588;
  color: white;
}

.sticky {
  position: fixed;
  bottom: 0;
  left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre style="font-size: 16px;">
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
    content
</pre>
<div class="footer">foo foo foo <br/>foo<br/>foo<br/></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...