To fix this with CSS you can add a padding to the Elements you want to jump to:
Example
Alternatively, you could add a border:
div{
height: 650px;
background:#ccc;
/*the magic happens here*/
border-top:42px solid #fff;
}
ul{
top: 0;
width: 100%;
height:20px;
position: fixed;
background: deeppink;
margin:0;
padding:10px;
}
li{
float:left;
list-style:none;
padding-left:10px;
}
div:first-of-type{
margin-top:0;
}
<!-- content to be placed inside <body>…</body> -->
<ul>
<li><a href="#s1">link 1</a>
<li><a href="#s2">link 2</a>
<li><a href="#s3">link 3</a>
<li><a href="#s4">link 4</a>
</ul>
<div id="s1" class="first">1</div>
<div id="s2">2</div>
<div id="s3">3</div>
<div id="s4">4</div>
However, this is not always applicable.
For a javascript solution you could use a click event attached to the anchor elements that scrolls an adjusted amount of pixels like following:
document.querySelector("a").addEventListener("click",function(e){
// dynamically determining the height of your navbar
let navbar = document.querySelector("nav");
let navbarheight = parseInt(window.getComputedStyle(navbar).height,10);
// show 5 pixels of previous section just for illustration purposes
let scrollHeight = document.querySelector(e.target.hash).offsetTop - navbarheight - 5;
/* scrolling to the element taking the height of the static bar into account*/
window.scroll(0,scrollHeight);
/*properly updating the window location*/
window.location.hash = e.target.hash;
/* do not execute default action*/
e.preventDefault();
});
nav{
position:fixed;
top:0;
left:0;
right:0;
height:40px;
text-align:center;
background:#bada55;
margin:0;
}
a{
display:block;
padding-top:40px;
}
#section1{
height:800px;
background:repeating-linear-gradient(45deg,#606dbc55,#606dbc55 10px,#46529855 10px,#46529855 20px);
}
#section2{
height:800px;
background:repeating-linear-gradient(-45deg,#22222255,#22222255 10px,#66666655 10px,#66666655 20px);
}
<nav>static header</nav>
<a href="#section2">jump to section 2</a>
<div id="section1">Section 1</div>
<div id="section2">Section 2</div>