<aside> <img src="/icons/light-bulb_blue.svg" alt="/icons/light-bulb_blue.svg" width="40px" />

As alluded to in the previous chapter, we were using jQuery to animate the scrolling of the viewport to wrap our heads around querying information from elements on our page, and using this information as parameters to the .animate() action. With exercises like this, we hope to convey the idea of developing general technical literacy skills here, as opposed to outlining functionality that you need to reproduce in your own work.

If you’re interested in seeing different ways to approach this idea, modern CSS lets you smoothly scroll between sections without the need for jQuery at all. Let’s take a cursory look at how it works.

</aside>

<aside> 🧁

Note

This is an entirely optional chapter.

</aside>

Appendix 1: CSS-only “smooth scrolling”

CSS smooth scrolling is a simple way to make page scroll behaviour feel illustrative and user-friendly. Instead of jumping instantly to a section when clicking an in-page anchor link (eg. #about), the page scrolls to that location smoothly. The nice thing about this approach is that you don’t need to do anything tricky: you just tell the html element selector that changes to the scroll offset should be smooth.

To enable this behaviour in CSS alone, add the following CSS to your stylesheet:

html {
	scroll-behavior: smooth;
}

Here’s a quick working example:

CSS-only smooth scrolling. Magic, right? The only catch is that you don’t have the ability to set the duration.

CSS-only smooth scrolling. Magic, right? The only catch is that you don’t have the ability to set the duration.

The HTML itself is quite simple: the anchors link to IDs within the page:

<section id="top">
	<a href="#contact">Contact section</a>
</section>

<p>Lorem ipsum...</p>

<section id="contact">
	<a href="#top">Back to top</a>
</section>

Appendix 2: .scrollIntoView()

In addition to the CSS-only smooth scrolling, there are some non-jQuery alternatives to moving the viewport. Browser support is very good in modern browsers (Chrome, Firefox, Edge, Safari), but not perfect on very old browsers.