Scenario
By applying an onFixed
class to the main
element of our page we cause the the nav
element to become fixed to the top of the page via the following CSS rule.
main.onFixed nav {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 1040;
}
Fixed positioning causes the nav
element to float over the element that it preceded, possibly covering it up, so we also want to move the section
element below it further down using padding.
This is our html
markup.
<body class="onFixed"><main>
<nav>
<a href="/" aria-current="page">Home</a>
<a href="/page2.html">Other page</a>
</nav>
<section>
<h1>Home page</h1>
</section>
</main>
</body>
Approach
This rule fixes the nav
element to the top of the page.
main.onFixed nav {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 1040;
}
Now that it’s fixed, it will float over the section
element, since the elements selector only add a top padding of 1rem
.
section {
padding: 1rem;
}
When we are using the onFixed
class on the main
element we want to make the section
padding 3rem
. This rule accomplishes that.
main.onFixed section {
padding: 3rem;
}