-1

I have a function which pushes my footer to the bottom of the page. It works by adding a margin to the top of the footer, however, i want to add a bg color to my content and with the margin this just leaves a big whitespace in the middle.

Can I extend the div above instead of adding the margin to the footer so that my bg color covers the page with no whitespace.

if ($('#footer').length) {
  var doc_height = $(window).height();
  var footer_top = $('#footer').position().top + $('#footer').height();
  
  if (footer_top < doc_height) {
    $('#footer').css('margin-top', (doc_height - footer_top) + 'px');
  }
}
#main_content {
  background-color: #f00
}

#footer {
  background-color: #0f0
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main_content">Some text</div>
<div id="footer">Some text</div>
Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
Paddy Hallihan
  • 1,624
  • 3
  • 27
  • 76
  • 1
    Why would you use js for this? Flex should work just fine – 0stone0 Aug 17 '20 at 15:43
  • Does this answer your question? [Align an element to bottom with flexbox](https://stackoverflow.com/questions/31000885/align-an-element-to-bottom-with-flexbox) – 0stone0 Aug 17 '20 at 15:47

2 Answers2

0

Can you please try flex as shown below:

#main_content{background-color:#f00}
#footer{background-color:#0f0}
body{
display:flex;
flex-direction:column;
height:100vh;
}
#main_content{
flex-basis:100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main_content">Some text</div>
<div id="footer">Some text</div>
Asutosh
  • 1,775
  • 2
  • 15
  • 22
0

You can do it without JavaScript. See the demo of my answer.

By using this code

  • You don't see an useless scroll bar beside the page when your content is little.
  • div elements are fitted to the page.
  • The main_content and footer will be stretched when their content is large.

Demo

body{
  margin:0;
  height:100vh;
}
#main_content{
  min-height:90%;
  background-color:#f00;
 }
#footer{
  min-height:10%;
  background-color:#0f0;
}
<div id="main_content">Some text</div>
<div id="footer">Some text</div>
Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98