[html] Scrolling to an Anchor using Transition/CSS3

I have a series of links which are using an anchor mechanism:

<div class="header">
    <p class="menu"><a href="#S1">Section1</a></p>
    <p class="menu"><a href="#S2">Section2</a></p>
    ...
</div>
<div style="width: 100%;">
<a name="S1" class="test">&nbsp;</a>
<div class="curtain">
Lots of text
</div>

<a name="S2" class="test">&nbsp;</a>
<div class="curtain">
lots of text
</div>
...
</div>

I am using the following CSS:

.test
{
    position:relative; 
    margin: 0; 
    padding: 0; 
    float: left;
    display: inline-block;
    margin-top: -100px; /* whatever offset this needs to be */
}

It's working fine. But of course, it's jumping from one section to the next when we click on the link. So I'd like to have a smooth transition, using a scroll of some sort to the start of selected section.

I think I read on Stackoverflow that this is not possible (yet) with CSS3 but I'd like a confirmation and also I'd like to know what 'could' be the solution. I am happy to use JS but I can't use jQuery. I tried to use an on click function on the link, retrieve the "vertical position" of the div that needs to be displayed but I was unsuccessful. I am still learning JS and don't know it well enough to come up with a solution of my own.

Any help/ideas would be greatly appreciated.

This question is related to html css

The answer is


I tried user18490 solution but there were some problems like:

  • Bouncing when clicked more than once
  • Bouncing if there isn't sufficient space below the target elements
  • Element is not defined
  • Problem of parent Element
  • e.t.c

Well after I edited and researched, I was able to come up with a solution. Hopefully it'll work for everyone

Just change the script tag to:

var html = document.documentElement

var body = document.body

var documentHeight = Math.max(body.scrollHeight, body.offsetHeight, html.scrollHeight, html.clientHeight, html.offsetHeight)

var PageHeight = Math.max(html.clientHeight || 0, window.innerHeight || 0)

function scrollDownTo(to, duration) {
    if (document.body.scrollTop == to) return;
    if ((documentHeight-to) < PageHeight) {
        to = documentHeight - PageHeight;
    }
    var diff = to - window.pageYOffset;
    var scrollStep = Math.PI / (duration / 10);
    var count = 0, currPos; ajaxe = 1
    var start = window.pageYOffset;
    var scrollInterval = setInterval(function(){
        if (window.pageYOffset != to) {
            count = count + 1;
            if (ajaxe > count) {
                clearInterval(scrollInterval)
            }
            currPos = start +  diff * (0.5 - 0.5 * Math.cos(count * scrollStep));
            scroll( 0, currPos)
            ajaxe = count
        }
        else { clearInterval(scrollInterval);}
    },20);
    }

function test (elID) {
    var dest = document.getElementById(elID);
    scrollDownTo((dest.getBoundingClientRect().top + window.pageYOffset), 500);
}

The HTML is still the same:

<div class="header">
    <p class="menu"><a href="#S1" onclick="test('S1'); return false;">S1</a></p>
    <p class="menu"><a href="#S2" onclick="test('S2'); return false;">S2</a></p>
    <p class="menu"><a href="#S3" onclick="test('S3'); return false;">S3</a></p>
    <p class="menu"><a href="#S4" onclick="test('S4'); return false;">S3</a></p>
</div>
<div style="width: 100%;">
    <div id="S1" class="curtain">
    blabla
    </div>
    <div id="S2" class="curtain">
    blabla
    </div>
    <div id="S3" class="curtain">
    blabla
    </div>
    <div id="S4" class="curtain">
    blabla
    </div>
 </div>

If you still encounter any issues kindly comment


You can find the answer to your question on the following page:

https://stackoverflow.com/a/17633941/2359161

Here is the JSFiddle that was given:

http://jsfiddle.net/YYPKM/3/

Note the scrolling section at the end of the CSS, specifically:

_x000D_
_x000D_
/*_x000D_
 *Styling_x000D_
 */_x000D_
_x000D_
html,body {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    position: relative; _x000D_
}_x000D_
body {_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
header {_x000D_
background: #fff; _x000D_
position: fixed; _x000D_
left: 0; top: 0; _x000D_
width:100%;_x000D_
height: 3.5rem;_x000D_
z-index: 10; _x000D_
}_x000D_
_x000D_
nav {_x000D_
width: 100%;_x000D_
padding-top: 0.5rem;_x000D_
}_x000D_
_x000D_
nav ul {_x000D_
list-style: none;_x000D_
width: inherit; _x000D_
margin: 0; _x000D_
}_x000D_
_x000D_
_x000D_
ul li:nth-child( 3n + 1), #main .panel:nth-child( 3n + 1) {_x000D_
background: rgb( 0, 180, 255 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 2), #main .panel:nth-child( 3n + 2) {_x000D_
background: rgb( 255, 65, 180 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 3), #main .panel:nth-child( 3n + 3) {_x000D_
background: rgb( 0, 255, 180 );_x000D_
}_x000D_
_x000D_
ul li {_x000D_
display: inline-block; _x000D_
margin: 0 8px;_x000D_
margin: 0 0.5rem;_x000D_
padding: 5px 8px;_x000D_
padding: 0.3rem 0.5rem;_x000D_
border-radius: 2px; _x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
ul li a {_x000D_
color: #fff;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
width: 100%;_x000D_
height: 500px;_x000D_
z-index:0; _x000D_
-webkit-transform: translateZ( 0 );_x000D_
transform: translateZ( 0 );_x000D_
-webkit-transition: -webkit-transform 0.6s ease-in-out;_x000D_
transition: transform 0.6s ease-in-out;_x000D_
-webkit-backface-visibility: hidden;_x000D_
backface-visibility: hidden;_x000D_
_x000D_
}_x000D_
_x000D_
.panel h1 {_x000D_
font-family: sans-serif;_x000D_
font-size: 64px;_x000D_
font-size: 4rem;_x000D_
color: #fff;_x000D_
position:relative;_x000D_
line-height: 200px;_x000D_
top: 33%;_x000D_
text-align: center;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
/*_x000D_
 *Scrolling_x000D_
 */_x000D_
_x000D_
a[ id= "servicios" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( 0px);_x000D_
transform: translateY( 0px );_x000D_
}_x000D_
_x000D_
a[ id= "galeria" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -500px );_x000D_
transform: translateY( -500px );_x000D_
}_x000D_
a[ id= "contacto" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -1000px );_x000D_
transform: translateY( -1000px );_x000D_
}
_x000D_
<a id="servicios"></a>_x000D_
<a id="galeria"></a>_x000D_
<a id="contacto"></a>_x000D_
<header class="nav">_x000D_
<nav>_x000D_
    <ul>_x000D_
        <li><a href="#servicios"> Servicios </a> </li>_x000D_
        <li><a href="#galeria"> Galeria </a> </li>_x000D_
        <li><a href="#contacto">Contacta  nos </a> </li>_x000D_
    </ul>_x000D_
</nav>_x000D_
</header>_x000D_
_x000D_
<section id="main">_x000D_
<article class="panel" id="servicios">_x000D_
    <h1> Nuestros Servicios</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="galeria">_x000D_
    <h1> Mustra de nuestro trabajos</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="contacto">_x000D_
    <h1> Pongamonos en contacto</h1>_x000D_
</article>_x000D_
</section>
_x000D_
_x000D_
_x000D_


I guess it might be possible to set some kind of hardcore transition to the top style of a #container div to move your entire page in the desired direction when clicking your anchor. Something like adding a class that has top:-2000px.

I did use JQuery because I'm to lazy too use native JS, but it is not necessary for what I did.

This is probably not the best possible solution because the top content just moves towards the top and you can't get it back easily, you should definitely use JQuery if you really need that scroll animation.

DEMO


Only mozilla implements a simple property in css : http://caniuse.com/#search=scroll-behavior

you will have to use JS at least.

I personally use this because its easy to use (I use JQ but you can adapt it I guess):

/*Scroll transition to anchor*/
$("a.toscroll").on('click',function(e) {
    var url = e.target.href;
    var hash = url.substring(url.indexOf("#")+1);
    $('html, body').animate({
        scrollTop: $('#'+hash).offset().top
    }, 500);
    return false;
});

just add class toscroll to your a tag


I implemented the answer suggested by @user18490 but ran into two problems:

  • First bouncing when user clicks on several tabs/links multiple times in short succession
  • Second, the undefined error mentioned by @krivar

I developed the following class to get around the mentioned problems, and it works fine:

export class SScroll{
    constructor(){
        this.delay=501      //ms
        this.duration=500   //ms
        this.lastClick=0
    }

    lastClick
    delay
    duration

    scrollTo=(destID)=>{
        /* To prevent "bounce" */
        /* https://stackoverflow.com/a/28610565/3405291 */
        if(this.lastClick>=(Date.now()-this.delay)){return}
        this.lastClick=Date.now()

        const dest=document.getElementById(destID)
        const to=dest.offsetTop
        if(document.body.scrollTop==to){return}
        const diff=to-document.body.scrollTop
        const scrollStep=Math.PI / (this.duration/10)
        let count=0
        let currPos
        const start=window.pageYOffset
        const scrollInterval=setInterval(()=>{
            if(document.body.scrollTop!=to){
                count++
                currPos=start+diff*(.5-.5*Math.cos(count*scrollStep))
                document.body.scrollTop=currPos
            }else{clearInterval(scrollInterval)}
        },10)
    }
}

UPDATE

There is a problem with Firefox as mentioned here. Therefore, to make it work on Firefox, I implemented the following code. It works fine on Chromium-based browsers and also Firefox.

export class SScroll{
    constructor(){
        this.delay=501      //ms
        this.duration=500   //ms
        this.lastClick=0
    }
    lastClick
    delay
    duration
    scrollTo=(destID)=>{
        /* To prevent "bounce" */
        /* https://stackoverflow.com/a/28610565/3405291 */
        if(this.lastClick>=(Date.now()-this.delay)){return}

        this.lastClick=Date.now()
        const dest=document.getElementById(destID)
        const to=dest.offsetTop
        if((document.body.scrollTop || document.documentElement.scrollTop || 0)==to){return}

        const diff=to-(document.body.scrollTop || document.documentElement.scrollTop || 0)
        const scrollStep=Math.PI / (this.duration/10)
        let count=0
        let currPos
        const start=window.pageYOffset
        const scrollInterval=setInterval(()=>{
            if((document.body.scrollTop || document.documentElement.scrollTop || 0)!=to){
                count++
                currPos=start+diff*(.5-.5*Math.cos(count*scrollStep))
                /* https://stackoverflow.com/q/28633221/3405291 */
                /* To support both Chromium-based and Firefox */
                document.body.scrollTop=currPos
                document.documentElement.scrollTop=currPos
            }else{clearInterval(scrollInterval)}
        },10)
    }
}

Here is a pure css solution using viewport units and variables that automatically scales to the device (and works on window resize). I added the following to Alex's solution:

        html,body {
            width: 100%;
            height: 100%;
            position: fixed;/* prevents scrolling */
            --innerheight: 100vh;/* variable 100% of viewport height */
        }

        body {
            overflow: hidden; /* prevents scrolling */
        }

        .panel {
            width: 100%;
            height: var(--innerheight); /* viewport height */

        a[ id= "galeria" ]:target ~ #main article.panel {
            -webkit-transform: translateY( calc(-1*var(--innerheight)) );
            transform: translateY( calc(-1*var(--innerheight)) );
        }

        a[ id= "contacto" ]:target ~ #main article.panel {
            -webkit-transform: translateY( calc(-2*var(--innerheight)) );
            transform: translateY( calc(-2*var(--innerheight)) );

If anybody is just like me willing to use jQuery, but still found himself looking to this question then this may help you guys:

https://html-online.com/articles/animated-scroll-anchorid-function-jquery/

_x000D_
_x000D_
$(document).ready(function () {_x000D_
            $("a.scrollLink").click(function (event) {_x000D_
                event.preventDefault();_x000D_
                $("html, body").animate({ scrollTop: $($(this).attr("href")).offset().top }, 500);_x000D_
            });_x000D_
        });
_x000D_
<a href="#anchor1" class="scrollLink">Scroll to anchor 1</a>_x000D_
<a href="#anchor2" class="scrollLink">Scroll to anchor 2</a>_x000D_
<p id="anchor1"><strong>Anchor 1</strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea.</p>_x000D_
<p id="anchor2"><strong>Anchor 2</strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas.</p>
_x000D_
_x000D_
_x000D_


Using the scroll-behavior CSS property:

(which is supported in modern browsers but not Edge):

_x000D_
_x000D_
a {
  display: inline-block;
  padding: 5px 7%;
  text-decoration: none;
}

nav, section {
  display: block;
  margin: 0 auto;
  text-align: center;
}

nav {
  width: 350px;
  padding: 5px;
}

section {
  width: 350px;
  height: 130px;
  overflow-y: scroll;
  border: 1px solid black;
  font-size: 0; 
  scroll-behavior: smooth;    /* <----- THE SECRET ---- */
}

section div{
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 8vw;
}
_x000D_
<nav>
  <a href="#page-1">1</a>
  <a href="#page-2">2</a>
  <a href="#page-3">3</a>
</nav>
<section>
  <div id="page-1">1</div>
  <div id="page-2">2</div>
  <div id="page-3">3</div>
</section>
_x000D_
_x000D_
_x000D_


Just apply scroll behaviour to all elements with this one-line code:

_x000D_
_x000D_
*{
scroll-behavior: smooth !important;
}
_x000D_
_x000D_
_x000D_