I've been trying quite many of css guides to put the footer at the bottom of the page and the example below is the one that I find the simplest.
html,
body,
#root {
height: 100%;
}
#root {
display: flex;
flex-direction: column;
}
nav {
position: sticky;
top: 0;
}
section {
flex: 1;
}
section>div {
height: 1000px;
}
<div id="root">
<header>Header</header>
<nav>Navigation</nav>
<section>
<div>Test</div>
<div>Test</div>
<div>Test</div>
</section>
<footer>Footer</footer>
</div>
It is working fine in terms of putting the footer at the bottom of the page, but the nav bar actually fails to follow the scroll at some point.
I am pretty sure this is because I've set the height of #root element to 100%.
The problem is even if I could guess "why" this is happening, I ain't sure "how" to fix this and keep the element (nav) staying at the top of the page.
Any helps, please?
CodePudding user response:
Add some javascript there to add a class sticky
to the navbar when the window gets scrolled and when the scroll is not on the top.
The class sticky
contains some simple CSS like:
position: fixed
to make your div fix anywhere you want;top: 0
to make it stick on top;width: 100%
to occupy all the screen width.
var navbarElement = document.getElementById("navbar");
var navbarScroll = navbarElement.offsetTop;
window.onscroll = function() {
addClassOnScroll()
};
function addClassOnScroll() {
if (window.pageYOffset >= navbarScroll) {
navbarElement.classList.add("sticky")
} else {
navbarElement.classList.remove("sticky");
}
}
html,
body,
#root {
height: 100%;
margin: 0;
}
#root {
display: flex;
flex-direction: column;
}
header {
padding: 15px
}
nav {
top: 0;
background-color: yellow;
}
section {
flex: 1;
}
section>div {
height: 1000px;
}
footer {
padding: 15px;
}
.sticky {
position: fixed;
top: 0;
width: 100%;
}
<div id="root">
<header>Header</header>
<nav id="navbar">Navigation</nav>
<section>
<div>Test</div>
<div>Test</div>
<div>Test</div>
</section>
<footer>Footer</footer>
</div>
CodePudding user response:
I think you're almost there. You just need to remove #root
with height: 100%
. Your nav
will be sticky in the entire page.
html,
body {
height: 100%;
}
#root {
display: flex;
flex-direction: column;
}
nav {
position: sticky;
top: 0;
}
section {
flex: 1;
}
section>div {
height: 1000px;
}
<div id="root">
<header>Header</header>
<nav>Navigation</nav>
<section>
<div>Test</div>
<div>Test</div>
<div>Test</div>
</section>
<footer>Footer</footer>
</div>