I\'m using a static bar at the top of my site, about 20px high. When I click an anchor link(for those who don\'t know, the navigation on wikipedia works like that. Click a t
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;
}
1
2
3
4
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);
}
jump to section 2
Section 1
Section 2