Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

animate - scrollTop in Css

I have a table of contents with html that when I click on send me the subtitle h1, h2 ect ..

<div class="idc-box">
<p class="idc-titulo">Contents</p>
<ul class="idc-lista">
  <li ><a href="#indice1">1 Índice 1</a>
  <ul>
    <li><a href="#subindice1">1.1 Subíndice 1</a></li>
    <li><a href="#subindice2">1.2 Subíndice 2</a></li>
  </ul>
</li>
</ul>
</div>

<div>
<h2 class="stitulo" id="indice1"><span class="titulo">Indice 1</span></h2>
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<h3 id="subindice1">Subindice 1.1</h3>
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor 

<h3 id="subindice2">Subindice 1.2</h3>
asda
<div>

In jquery when I want to put a space above the title or subtitle I used animate - scrollTop :

<script type='text/javascript'>
$("#idc-box a").click(function(e){


    var enlace = $(this).attr('href');

    $('html, body').animate({
        scrollTop: ($(enlace).offset().top - 90) + 'px'
    }, 500)
})
</script>

but now I can not use query if not CSS because I'm using AMP = = Accelerated Mobile Pages How can I do that equivalent in CSS?

like image 494
juan Avatar asked Dec 14 '25 08:12

juan


1 Answers

There is a native CSS feature that controls scroll behaviour without having to use jQuery, called scroll-behavior:

body {
  background-color: #333;
}

.scrolling-box {
  scroll-behavior: smooth; // Animates scrolling - "smooth" scrolling
  padding: 15px;
  background-color: #eaeaea;
  display: block;
  width: 200px;
  height: 120px;
  overflow-y: scroll;
  text-align: center;
}

section {
  margin-top: 20px;
  height: 100px;
}
<div class="scrolling-box">
  <a href="#1">1</a>
  <a href="#2">2</a>
  <a href="#3">3</a>
  <section id="1">This is the first section</section>
  <section id="2">This is the second section</section>
  <section id="3">This is the third section</section>
</div>
like image 143
Okba Avatar answered Dec 16 '25 05:12

Okba