I have a situation where I use several sliders on the page due to which the actual height of the page changes
Let’s say my html
height is 600px but due to some sliders the actual page height is 1000px
And because of this, when I try to stick the footer to the bottom using position: absolute
and bottom: 0
, I have it placed at the end of the html
height
I used an example to show how everything looks like for me
If I use position: relative
then on other pages where the height is small, it will not be at the bottom
How can I stick the footer to the bottom of the page in this case?
I have also tried wrapping the entire html
content in a class .wrapper { height: 100%; display: flex; flex-direction: column; }
and for the footer use position: relative
and margin-top: auto
This kind of helped, but then there were problems with the blocks that come after the html
, they lost their width..
html {
height: 500px;
}
.main-content {
padding: 200px;
text-align: center;
}
.content {
padding: 300px;
text-align: center;
}
.footer {
padding: 40px 0;
position: absolute;
width: 100%;
bottom: 0;
text-align: center;
background: gray;
}
<html>
<div class="main-content"> MAIN CONTENT</div>
<div class="content">CONTENT</div>
<footer class="footer">FOOTER</footer>
</html>
3
Answers
An easy way to solve this issue is to set a minimum height on the block level element before the footer and to ditch all the positioning.
Let’s say that you’d want to have a footer that’s
50px
high. Your element before that should be at least100vh - 50px
high in order to cover the full height of the screen even if the content isn’t that big. You can do this with calc.I took the liberty and simplified your HTML structure. You can place anything inside
main-content
and the footer will stay at the bottom. If you for example modify the code to havemin-height: 200vh
instead of the calc……you can see that the footer stays at the bottom of the page even if
main-content
is bigger than what I provided in the first snippet.Grid is awesome for these types of designs where you want to have a fixed footer/header/sidebar along with with some other scrolling content.
In the example below, there are 3 rows. Using a fractional for the height (1fr) on the main content, it will essentially grow to fill whatever space is available in the grid, after taking into account the height of the other rows. In this case, the footer has a fixed height and uses
max-content
for it’s height, while the aside uses auto, so it grows to adjust to its contents. Playing with the various grid-template-rows is incredibly powerful.Run the snippet below, and then choose the full page option to see how it works at different viewport sizes.
You can use
flexbox
. Uncommentheight
property inbody
to see the changes.Check the elements
html
,body
,main
andfooter
in the code below.Resources:
CSS Tricks | Flexbox
CSS Tricks | Flexbox and Auto Margins
Dev | Stick Footer to The Bottom of The Page