Utilizing the power of flex box CSS, along with a structured HTML layout:
<body>
<header></header>
<main></main>
<footer></footer>
</body>
Technique 1: (fixed height footer) Applying display:flex
and flex-direction:column
to the body
. Adding flex:1
(flex-grow:1
) to the main
element.
The main section will expand vertically to fill any available space, ensuring the footer stays at the bottom.
body {
display: flex;
flex-direction: column;
min-height: 100vh;
margin:0;
}
header {
background-color: #cffac7;
height:50px;
}
main {
background-color: #f8e2ff;
flex:1;
}
footer {
background-color: #fceec7;
height:50px;
}
<header></header>
<main></main>
<footer></footer>
Technique 2: (fixed height footer) Using display:flex
and flex-direction:column
on the body
. Applying margin-top:auto
to the footer
.
By utilizing auto margins in flex containers, the footer automatically sticks to the bottom by absorbing free space. This doesn't require the main section to have content or a specific height. In this scenario, no flex rules are set for main, defaulting to flex:initial
(flex: 0 1 auto
).
body {
display: flex;
flex-direction: column;
min-height: 100vh;
margin:0;
}
header {
background-color: #cffac7;
height:50px;
}
main {
background-color: #f8e2ff;
}
footer {
background-color: #fceec7;
height:50px;
margin-top:auto;
}
<header></header>
<main></main>
<footer></footer>
Technique 3: (fluid height footer) Similar to technique #1 but with elements having no inherent height. By adjusting the flex-grow
values of main
, header
, and footer
, main
expands much faster than the others.
body {
display: flex;
flex-direction: column;
min-height: 100vh;
margin:0;
}
header {
background-color: #cffac7;
flex:1;
}
main {
background-color: #f8e2ff;
flex:5;
}
footer {
background-color: #fceec7;
flex:1
}
<header></header>
<main></main>
<footer></footer>