How to Push Footer to Bottom of the Screen with Using CSS Flex
In this article, I will show you how to use CSS Flexbox and the ‘justify-content’ property to keep the footer at the bottom of the screen even if there is not enough content to fill the height of the screen.
Basics of CSS and Flexbox
CSS (Cascading Style Sheets) is a language used to define the appearance of websites. One of the most powerful tools in CSS is Flexbox, which allows horizontal placement of elements. Flexbox can also be used vertically, and we will use this feature to accomplish our goal.
Step 1: Set the Body Element as a Flex Container
The first step is to set the body element of the website as a Flex container:
body {
display: flex;
flex-direction: column;
justify-content: space-between;
min-height: 100vh;
}
display: flex;
sets the body element as a Flex container.flex-direction: column;
specifies that the content of body element will be stacked vertically.justify-content: space-between;
ensures that body element’s contents are evenly distributed within the body element’s height. This means that the footer already will stay at the bottom of the screen if the content does not fill the entire screen height.min-height: 100vh;
sets the minimum height of the body element to 100% of the screen height.
Step 2: Set Top Margin for the Footer
Next, we want to make sure that the elements above the footer stay stacked at the top of the screen if their combined height does not cover the screen height minus the height of the footer. To achieve this, we can set the top margin of the footer to ‘auto’:
footer {
margin-top: auto;
}
This code sets the top margin of the footer to automatically push itself as far down as possible. In this case, it pushes the elements above it upward.