To keep the navbar in place, you can utilize the CSS properties position:fixed
and top:0
. Additionally, set the height
of the navbar to a specific value and match this value with the padding-top
property for each anchor element.
By following this approach, clicking on navigation links will bring the top of the anchor elements to the browser's viewport. While some parts may be covered by the navbar (due to the z-index:1
setting), this will only include the padding area which is usually invisible without borders or background colors. The content will then display correctly below the navbar.
Below is an example code snippet:
CSS:
#navbar
{
position: fixed;
top: 0;
z-index: 1;
height: 1em;
margin: 0;
}
.heading
{
padding-top: 1em;
}
- HTML:
<div id="content">
<h2 id="one" class="heading">Section 1</h2>
...
<h2 id="two" class="heading">Section 2</h2>
...
<h2 id="three" class="heading">Section 3</h2>
...
</div>
<div id="navbar">
<a href="#one">Section 1</a>
<a href="#two">Section 2</a>
<a href="#three">Section 3</a>
</div>
It's important to note that this method doesn't address dynamic changes in navbar height. In such cases, implementing JavaScript, as suggested by Bryan, may be the most straightforward solution.
PS - If the element with the specified ID has display:block
or display:inline-block
, the padding may impact page layout, which could be undesired.