How to get the footer to stay at the bottom of a Web page?

Problem:

A webpage contains some contents with footer.  You want to keep the footer always at the bottom whether the contents go pretty far down or not even enough content to go all the way to the bottom of the screen.

Solution:

Two solutions regarding this problem are mentioned here-

Solution-1:

The code:

HTML:

<div class="content">here are some contents</div>
<footer>This is my footer</footer>

CSS:

.content {
    min-height: calc(100vh - 50px); /* 50px for footer*/
    background: red;
}
footer {
    height: 50px;
    background: pink;
}

Explanation:

The min-height property is used to set the minimum height of an element. 1vh(viewport height)=1% of the browser’s height. So, 100vh means 100% of the browser’s height. Here (100vh-50px) value tells the contents to leave 50px space in the bottom. By setting the value of footer to 50px, the footer takes that bottom place.

N.B: If you want to change the height of the footer, you have to change both footer height (suppose x) and min-height (100vh-x).

Solution-2:

The code:

HTML:

<div class="content">here are some contents
    <div class=”help”></div>
</div>
<footer>This is my footer</footer>

CSS:

html, body {
    height: 100%;
    }
    .content {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -5em;
    }
    .footer, .help{
    height: 5em;
    background-color: pink;
    }

Explanation:

There is a negative value is used for margin-bottom property. The negative value of margin defines the contents of the next element (here footer) overlapping the previous element. As help div is used before ending the content div and the height is equal to the height of footer (5em), footer div overlaps the help div. For that reason, help div have no element.

Important things to know:

  1. Negative margin should be equal to the height of the footer and help div.
  2. There should be no content inside the help div because it is a hidden element which helps the footer to stay at the bottom.
  3. Margin shorthand property is margin: top, right, bottom, left. As there are three values. It means that the second value is used for both right and left value and they are same. So in this case top-0, right-auto, left-auto, bottom-5em.