A modern "sticky footer" solution would use flexbox.
tl;dr:: set container (body) to display:flex;flex-direction:column
and the child (footer) you want to move down to margin-top:auto
.
First, we set the body to "flex" its items vertically, making sure that it is 100% height.
Then we set flex: 0 0 50px
on the footer element, which means: "don't grow, don't shrink, and have a height of 50px". We could in fact, omit flex
attribute entirely and just go with height:50px
.
We can set display:flex
on things like the <body>
itself somewhat recklessly, because children of a flex container have a implicit value of flex: 0 1 auto
(aka flex:initial
) if omitted, which is (almost) equivalent to flex:none
(which is shorthand for
flex:0 0 auto
):
The item is sized according to its width and height properties. It
shrinks to its minimum size to fit the container, but does not grow to
absorb any extra free space in the flex container.(MDN)
As far as the sticky part, it's the margin-top:auto
on the footer that gives us what we want. Applied within a flex container, auto margins take on a new meaning, instead of the usual "get equal amount of free space", they mean "absorb ALL available free space".
From the spec (8.1. Aligning with auto margins):
Prior to alignment via justify-content and align-self, any positive
free space is distributed to auto margins in that dimension.
Stated more simply:
If you apply auto margins to a flex item, that item will automatically
extend its specified margin to occupy the extra space in the flex
container
Aside: the "normal" flexbox layout approach would probably be to flex a middle section ala <div id="main>...</div>
to 100% vertically, which also would make a footer "stick" to the bottom. This approach shows us the flexible box model is, in fact, flexible enough to let us resize/move isolated elements.
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
#footer {
background-color: #efefef;
flex: 0 0 50px;/*or just height:50px;*/
margin-top: auto;
}
<p>we've assumed only that there's random space-taking content above the footer...</p>
<p>lorem ipsum dolor flex...</p>
<div>
<p>random content.</p><p>random content.</p><p>random content.</p><p>random content.</p>
</div>
<div id="footer">FOOTER</div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…