CSS leakage and filling (I) – when the page content is insufficient to cover the screen height and there are scrollbars, the footer always displays at the bottom

Time:2020-1-14

To record the skills often used in a project, the footer area (such as copyright information) should always be at the bottom of the page. It is obviously not advisable to use fixed positioning, because to ensure that the page height is greater than the screen height, the footer area should keep at the bottom with the page scrolling, as shown in the following figure:

CSS leakage and filling (I) - when the page content is insufficient to cover the screen height and there are scrollbars, the footer always displays at the bottom

CSS leakage and filling (I) - when the page content is insufficient to cover the screen height and there are scrollbars, the footer always displays at the bottom

  • Tip: the following two methods are only applicable to the situation where the height of the footer area is fixed

Method 1

Page structure:

<div class="wrapper">
    <div class="main-container">
        < div class = "box" > this is the main content < / div >
    </div>
    < footer > this is the bottom < / footer >
</div>
  • Key CSS
html,body{
    height: 100%;
}
.wrapper{
    height: 100%;
}
.main-container{
    min-height: 100%;
    box-sizing: border-box;
    padding-bottom: 40px;
}
footer{
    margin-top: -40px;
}

As in the code above, the main content area and footer area must be in a side-by-side relationship. Set the main container to border box, that is, the inner margin and border of the element are drawn within the set height. We set min height to 100%, that is, the minimum height is to cover the whole screen. Padding bottom is in the border box box, leaving a blank block with a height of 40px. The margin top of the footer is – 40px (if the footer has a set height, the value of padding bottom should be based on the footer height), that is, pull up into the blank block, and the minimum height of the main container is the whole screen, so the page content can also be displayed at the bottom.

Method two

Page structure

<div class="wrapper">
    <div class="main-container">
        < div class = "box" > this is the main content < / div >
    </div>
    < footer > this is the bottom < / footer >
</div>

Key CSS

html,body{
    height: 100%;
}
.wrapper{
    min-height: 100%;
    position: relative;
}

.main-container{
    padding-bottom: 40px;
}

footer{
    position: absolute;
    bottom: 0;
    height: 40px;
}

As for the above code, absolute positioning is used. Compared with wrapper, it is at the bottom, which is similar to the first method.