a href to an identifier with margin

1

My question is if you can do a href to an id but send you 5px higher or 10px for example:

<a href = "#nosotros"></a>
<div id = "nosotros"></div>

That looks like this

and not stuck up like here

    
asked by Sergio Camilo 07.03.2017 в 18:45
source

3 answers

2

I think it's possible to do it with jQuery. You can even cheer up a bit. With these elements:

I would add something like this:

<script src="https://code.jquery.com/jquery-2.2.4.min.js"
    integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
    crossorigin="anonymous"></script>

<div id='hola'><h2>Hola</h2></div>
<a data-href='#hola' href='#'>Ir a hola</a>

<script>
    $(function(){
        $('a').click(function(e){
            e.preventDefault();
            var div = $(this).data('href');
            var y = $(div).offset().top - 50;
            $('body,html').stop(true,true).animate({                                
                scrollTop: y
            },1000);
        });
    });

</script>

I hope it serves you.

    
answered by 07.03.2017 / 19:06
source
1

The property that can serve you is padding .

CSS Example

.big {
  height: 600px;
}

#nosotros {
  padding-top: 10px;
}
<a href="#nosotros">Nosotros</a>
<div class="big"></div>
<div id="nosotros">
  <h1>Nosotros</h1>
</div>
<div class="big"></div>

However, it is not viable because if you want to give a margin higher than 50px, you would have to give it a padding-top: 50px which would be horrible. It would be best to use JavaScript for this case.

Example JS

let anchors = document.querySelectorAll('[anchor]');
[].forEach.call(anchors, function(anchor) {
  anchor.addEventListener('click', function(e) {
    e.preventDefault();
    let el = document.querySelector(this.getAttribute('href'));
    // 50px más abajo
    let top = el.getBoundingClientRect().top + window.scrollY - 50;
    window.scrollTo(0, top);
  });
});
.big {
  height: 600px;
}
<a anchor href="#nosotros">Nosotros</a>
<div class="big"></div>
<div id="nosotros">
  <h1>Nosotros</h1>
</div>
<div class="big"></div>
    
answered by 07.03.2017 в 19:19
-1

Sure, put this style

<style>
  a{
   margin-top: 10px;
   display: block;
  }
</style>
    
answered by 07.03.2017 в 19:00