HTML/CSS: When I click on the link it does not go to the right point of the page

Asked

Viewed 77 times

1

I have a page that has a simple top menu that has some links that take the user straight to the section referring to this link:

<style>
    nav {
        width: 100%;
        height: 60px;
        position: fixed;
        top: 0;
        background-color: black;
    }

    section {
        width: 100%;
        height: 100vh;
    }

    #sec1 {  
        background-color: red;  
    }

    #sec2 {
        background-color: blue;
    }

    #sec3 {
        background-color: green;
    }
</style>

<nav>
    <a href="#sec1">Link 1</a>
    <a href="#sec2">Link 2</a>
    <a href="#sec3">Link 3</a>
</nav>

<section id="sec1">
    ...
</section>

<section id="sec2">
    ...
</section>

<section id="sec3">
    ...
</section>

This navigation menu is set at the top, and because of this when I go straight to the section it covers part of the content, thus generating the need for the user to scroll the page to see this excerpt. My question is: is there any way to control this scrolling with CSS or Javascript? I thought about doing this by giving a padding-top in all the sections, but it doesn’t seem to be the right way.

  • I did not understand why the negative votes, I made a mistake in the question?

  • puts a padding-top;in the body, regulates according to what you like. padding-top: 70px, for example.

1 answer

3


Anyway you need to put one padding-top in the body of the same height as nav, but the first section will overlap.

body{
   margin: 0;
   padding-top: 60px;
}

See that I reset also the margin to eliminate the standard spacing of body.

With Javascript you can calculate the position of the window scroll and position the section just below the nav:

const menu = document.querySelectorAll("nav a");
for(let i of menu){
   i.onclick = function(){
      let nav_height = document.querySelector("nav").clientHeight; // altura da nav
      setTimeout(function(){
         let scrol = window.scrollY; // posição do scroll da janela
         window.scrollTo(0, scrol-nav_height);
      }, 10);
   }
}
body{
margin: 0;
padding-top: 60px;
}
nav {
     width: 100%;
     height: 60px;
     position: fixed;
     top: 0;
     background-color: black;
 }

a{color: white}

 section {
     width: 100%;
     height: 100vh;
 }

 #sec1 {  
     background-color: red;  
 }

 #sec2 {
     background-color: blue;
 }

 #sec3 {
     background-color: green;
 }
<nav>
    <a href="#sec1">Link 1</a>
    <a href="#sec2">Link 2</a>
    <a href="#sec3">Link 3</a>
</nav>

<section id="sec1">
    sec1
</section>

<section id="sec2">
    sec2
</section>

<section id="sec3">
    sec3
</section>

  • Thanks Sam, it worked perfect!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.