<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- To place the footer at the bottom of the page -->
<style>
html,
body {
height: 100%;
}
#root {
min-height: 100%;
display: flex;
flex-direction: column;
}
header {
position: absolute; /* To pull the header out of the document flow */
}
main {
flex: 1;
}
</style>
<title>Document</title>
</head>
<body>
<div id="root">
<header>
<h1></h1>
<nav></nav>
</header>
<main></main>
<footer></footer>
</div>
</body>
</html>
Let's say h1 and nav is placed within header tag and this would look like below:
What I want to achieve is keeping the nav
tag on top of the page while the h1
tag is being scrolled as usual:
I've tried adding position: sticky;
and top: 0;
, but it doesn't seem to be working as the nav tag is placed within the header tag.
Should I be using JavaScript to achieve this? or is it possible to solve with plain CSS only?
html,
body {
height: 100%;
}
body {
margin: 0;
}
#root {
min-height: 100%;
display: flex;
flex-direction: column;
}
header {
position: absolute; /* To pull the header out of the document flow */
left: 0;
right: 0;
}
header h1 {
text-align: center;
}
nav {
margin: 0 auto;
position: sticky;
top: 0;
}
nav > ul {
margin: 0;
padding: 0;
list-style-type: none;
display: flex;
}
nav > ul li {
margin: 0 10px;
}
nav > ul li a {
color: #000000;
text-decoration: none;
font-size: 1.1rem;
font-weight: 600;
letter-spacing: 1px;
}
nav > ul li a:hover {
color: #bd8b4f;
}
main {
flex: 1;
min-height: 1500px;
}
footer {
padding: 40px 0;
color: #ffffff;
background-color: #683d29;
text-align: center;
}
footer > div a {
color: #ffffff;
text-decoration: none;
}
footer > div a:hover {
color: #683d29;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="root">
<header>
<h1>Test Page</h1>
<nav>
<ul>
<li>
<a href="#">Nav</a>
</li>
<li>
<a href="#">Nav</a>
</li>
<li>
<a href="#">Nav</a>
</li>
<li>
<a href="#">Nav</a>
</li>
<li>
<a href="#">Nav</a>
</li>
</ul>
</nav>
</header>
<main></main>
<footer>
<div>Copyright 2022. <a href="#">Test</a> All rights reserved.</div>
</footer>
</div>
</body>
</html>