Tag: Scroll

How to Create a Shrinking Header on Scroll Without JavaScript

Imagine a header of a website that is nice and thick, with plenty of padding on top and bottom of the content. As you scroll down, it shrinks up on itself, reducing some of that padding, making more screen real estate for other content.

Normally you would have to use some JavaScript to add a shrinking effect like that, but there’s a way to do this using only CSS since the introduction of position: sticky.

Let me just get this out there: I’m generally not a fan of sticky headers. I think they take up too much of the screen’s real estate. Whether or not you should use sticky headers on your own site, however, is a different question. It really depends on your content and whether an ever-present navigation adds value to it. If you do use it, take extra care to avoid inadvertently covering or obscuring content or functionality with the sticky areas — that amounts to data loss.

Either way, here’s how to do it without JavaScript, starting with the markup. Nothing complicated here — a <header> with one descendant <div> which, intern, contains the logo and navigation.

<header class="header-outer">   <div class="header-inner">     <div class="header-logo">...</div>     <nav class="header-navigation">...</nav>   </div> </header>

As far as styling, we’ll declare a height for the parent <header> (120px) and set it up as a flexible container that aligns its descendant in the center. Then, we’ll make it sticky.

.header-outer {   display: flex;   align-items: center;   position: sticky;   height: 120px; }

The inner container contains all the header elements, such as the logo and the navigation. The inner container is in a way the actual header, while the only function of the parent <header> element is to make the header taller so there’s something to shrink from.

We’ll give that inner container, .header-inner, a height of 70px and make it sticky as well.

.header-inner {   height: 70px;   position: sticky;   top: 0;  }

That top: 0? It’s there to make sure that the container mounts itself at the very top when it becomes sticky.

Now for the trick! For the inner container to actually stick to the “ceiling” of the page we need to give the parent <header> a negative top value equal to the height difference between the two containers, making it stick “above” the viewport. That’s 70px minus 120px, leaving with with — drumroll, please — -50px. Let’s add that.

.header-outer {   display: flex;   align-items: center;   position: sticky;   top: -50px; /* Equal to the height difference between header-outer and header-inner */   height: 120px; }

Let’s bring it all together now. The <header> slides out of frame, while the inner container places itself neatly at the top of the viewport.

We can extend this to other elements! How about a persistent alert?

While it’s pretty awesome we can do this in CSS, it does have limitations. For example, the inner and outer containers use fixed heights. This makes them vulnerable to change, like if the navigation elements wrap because the number of menu items exceeds the amount of space.

Another limitation? The logo can’t shrink. This is perhaps the biggest drawback, since logos are often the biggest culprit of eating up space. Perhaps one day we’ll be able to apply styles based on the stickiness of an element…


The post How to Create a Shrinking Header on Scroll Without JavaScript appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , , ,

Going From Solid to Knockout Text on Scroll

Here’s a fun CSS trick to show your friends: a large title that switches from a solid color to knockout text as the background image behind it scrolls into place. And we can do it using plain ol’ HTML and CSS!

This effect is created by rendering two containers with fixed <h1> elements. The first container has a white background with knockout text. The second container has a background image with white text. Then, using some fancy clipping tricks, we hide the first container’s text when the user scrolls beyond its boundaries and vice-versa. This creates the illusion that the text background is changing.

Before we begin, please note that this won’t work on older versions of Internet Explorer. Also, fixed background images can be cumbersome on mobile WebKit browsers. Be sure to think about fallback behavior for these circumstances.

Setting up the HTML

Let’s start by creating our general HTML structure. Inside an outer wrapper, we create two identical containers, each with an <h1> element that is wrapped in a .title_wrapper.

<header>    <!-- First container -->   <div class="container container_solid">     <div class="title_wrapper">       <h1>The Great Outdoors</h1>     </div>   </div>    <!-- Second container -->   <div class="container container_image">     <div class="title_wrapper">       <h1>The Great Outdoors</h1>     </div>   </div>  </header>

Notice that each container has both a global .container class and its own identifier class — .container_solid and .container_image, respectively. That way, we can create common base styles and also target each container separately with CSS.

Initial styles

Now, let’s add some CSS to our containers. We want each container to be the full height of the screen. The first container needs a solid white background, which we can do on its .container_solid class. We also want to add a fixed background image to the second container, which we can do on its .container_image class.

.container {   height: 100vh; }  /* First container */ .container_solid {   background: white; }  /* Second container */ .container_image {   /* Grab a free image from unsplash */   background-image: url(/path/to/img.jpg);   background-size: 100vw auto;   background-position: center;   background-attachment: fixed; }

Next, we can style the <h1> elements a bit. The text inside .container_image can simply be white. However, to get knockout text for the <h1> element inside container_image, we need to apply a background image, then reach for the text-fill-color and background-clip CSS properties to apply the background to the text itself rather than the boundaries of the <h1> element. Notice that the <h1> background has the same sizing as that of our .container_image element. That’s important to make sure things line up.

.container_solid .title_wrapper h1 {   /* The text background */   background: url(https://images.unsplash.com/photo-1575058752200-a9d6c0f41945?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ);   background-size: 100vw auto;   background-position: center;      /* Clip the text, if possible */   /* Including -webkit` prefix for bester browser support */   /* https://caniuse.com/text-stroke */   -webkit-text-fill-color: transparent;   text-fill-color: transparent;   -webkit-background-clip: text;   background-clip: text;      /* Fallback text color */   color: black; }  .container_image .title_wrapper h1 {   color: white; }

Now, we want the text fixed to the center of the layout. We’ll add fixed positioning to our global .title_wrapper class and tack it to the vertical center of the window. Then we use text-align to horizontally center our <h1> elements.

.header-text {   display: block;   position: fixed;    margin: auto;   width: 100%;   /* Center the text wrapper vertically */   top: 50%;   -webkit-transform: translateY(-50%);       -ms-transform: translateY(-50%);           transform: translateY(-50%); }  .header-text h1 {   text-align: center; }

At this point, the <h1> in each container should be positioned directly on top of one another and stay fixed to the center of the window as the user scrolls. Here’s the full, organized, code with some shadow added to better see the text positioning.

Clipping the text and containers

This is where things start to get really interesting. We only want a container’s <h1> to be visible when its current scroll position is within the boundaries of its parent container. Normally this can be solved using overflow: hidden; on the parent container. However, with both of our <h1> elements using fixed positioning, they are now positioned relative to the browser window, rather than the parent element. In this case using overflow: hidden; will have no effect.

For the parent containers to hide fixed overflow content, we can use the CSS clip property with absolute positioning. This tells our browser hide any content outside of an element’s boundaries. Let’s replace the styles for our .container class to make sure they don’t display any overflowing elements, even if those elements use fixed positioning.

.container {   /* Hide fixed overflow contents */   clip: rect(0, auto, auto, 0);    /* Does not work if overflow = visible */   overflow: hidden;    /* Only works with absolute positioning */   position: absolute;    /* Make sure containers are full-width and height */   height: 100vh;   left: 0;   width: 100%; }

Now that our containers use absolute positioning, they are removed from the normal flow of content. And, because of that, we need to manually position them relative to their respective parent element.

.container_solid {   /* ... */    /* Position this container at the top of its parent element */   top: 0; }  .container_image {   /* ... */  /* Position the second container below the first container */   top: 100vh; }

At this point, the effect should be taking shape. You can see that scrolling creates an illusion where the knockout text appears to change backgrounds. Really, it is just our clipping mask revealing a different <h1> element depending on which parent container overlaps the center of the screen.

Let’s make Safari happy

If you are using Safari, you may have noticed that its render engine is not refreshing the view properly when scrolling. Add the following code to the .container class to force it to refresh correctly.

.container {   /* ... */    /* Safari hack */   -webkit-mask-image: -webkit-linear-gradient(top, #ffffff 0%,#ffffff 100%); }

Here’s the complete code up to this point.

Time to clean house

Let’s make sure our HTML is following accessibility best practices. Users not using assistive tech can’t tell that there are two identical <h1> elements in our document, but those using a screen reader sure will because both headings are announced. Let’s add aria-hidden to our second container to let screen readers know it is purely decorative.

<!-- Second container --> <div class="container container_image" aria-hidden="true">   <div class="title_wrapper">     <h1>The Great Outdoors</h1>   </div> </div>

Now, the world is our oyster when it comes to styling. We are free to modify the fonts and font sizes to make the text just how we want. We could even take this further by adding a parallax effect or replacing the background image with a video. But, hey, at that point, just be sure to put a little additional work into the accessibility so those who prefer less motion get the right experience.

That wasn’t so hard, was it?


The post Going From Solid to Knockout Text on Scroll appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , , ,
[Top]

How to Use the Locomotive Scroll for all Kinds of Scrolling Effects

I was recently looking for a way to perform scrolling effects on a project and I stumbled on the Locomotive Scroll library. It lets you perform a variety of scrolling effects, like parallax and triggering/controlling animations at scroll points.

You might also call it a “smooth scrolling” library, but it doesn’t leverage native smooth scrolling — it does just the opposite by virtualizing scrolling and ensuring it’s always smooth. You could probably consider this “scrolljacking” so if you hate that generally, you might hate this, but UX research seems rather mixed on whether it’s actually bad or not. The homepage will give you a good sense of how it works and feels.

Let’s look at the basics of using Locomotive-Scroll JavaScript and how to leverage it to for delightful user experiences.

What is Locomotive Scroll?

Here’s what they say:

Locomotive scroll is a simple scroll library, built as a layer on top of ayamflow’s virtual-scroll, it provides smooth scrolling with support for parallax effects, toggling classes, and triggering event listeners when elements are in the viewport.

In other words, it detects when elements are in the viewport and then alters CSS transform property values on those elements to create scrolling effects.

Oftentimes scrolling effects are called parallax meaning some elements are made to look like they are deep in the background, making them appear to move slower than other elements that are closer to the foreground while scrolling is taking place. Imagine looking out the window from a moving car. The trees far away seems to slowly drift by where the fence right along the road zips quickly by. Sort of like the effect here in this pen from Sarah Drasner:

Here’s how it works

Locomotive Scroll works primarily through specific attributes in the HTML. Elements with these attributes trigger event listeners in JavaScript when they are in the viewport, then apply CSS transform values as inline styles.

There are two key attributes to always call upon Locomotive:

  • data-scroll: detects whether or not an element is in the viewport
  • data-scroll-container: wraps all the HTML content you want to watch for scrolling

Here’s what we’re talking about when we say that the transform property values are updated in the HTML as inline styles.

Notice how, as soon as an element with Locomotive’s data- attributes comes into the viewport, the CSS transform values are are updated.

Let’s set this up

We can use the library right as a <script> tag if we’d like. It’s on CDNs, so like:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/locomotive-scroll@3.5.4/dist/locomotive-scroll.css">  <script src="https://cdn.jsdelivr.net/npm/locomotive-scroll@3.5.4/dist/locomotive-scroll.min.js">

Now we look for the container and kick off the library:

const scroller = new LocomotiveScroll({   el: document.querySelector('[data-scroll-container]'),   smooth: true });

The library is on npm as well, so we can use it that way in our build instead with the typical npm install locomotive-scroll, then:

import LocomotiveScroll from 'locomotive-scroll';  const scroll = new LocomotiveScroll();

That means we could use them off Skypack too, like:

That’s really all there is to the setup! It’s pretty plug-and-play like that.

Here are some examples

You can probably think of some pretty nice use cases for something like this, but let’s go over a few examples where you might use Locomotive Scroll.

Let’s start with this one:

That HTML has all kinds of data- attributes going on in there. We’ve already looked at data-scroll and data-scroll-container. Here’s what the rest are and what they do:

  • data-scroll-section : Defines a scrollable section. For better performance, it’s a good idea to split pages into sections.
  • data-scroll-direction: Defines the vertical or horizontal direction that an element moves.
  • data-scroll-speed: Specifies the speed an element moves. A negative value reverses the direction, but only vertically, unless data-scroll-direction is applied on the same element.
  • data-scroll-sticky: Specifies an element that sticks to the viewport as long as the target element is still in view.
  • data-scroll-target: Targets a particular element. It takes in an ID selector, which is unique compared to the other attributes.

So, let’s say we are using the data-scroll-sticky attribute. We always have to set a data-scroll-target attribute as well, because the target element is usually the container holding the other elements.

<div class="container" id="stick" data-scroll-section >   <p data-scroll data-scroll-sticky data-scroll-target="#stick">     Look at me, I'm going to stick when you scroll pass me.   </p> </div>

Now that we’ve picked one apart, here are a couple of others:

You can also use LocoMotive-Scroll in other frameworks, too. Here’s an example in React:

Scroll aboard!

I can not emphasize the power of Locomotive Scroll enough. I needed to add scroll effects to a side project I was working on, and this was super quick and easy to use. I hope you’re able to use it on a project and experience how great it is for scrolling effects.


The post How to Use the Locomotive Scroll for all Kinds of Scrolling Effects appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , ,
[Top]

Doom Damage Flash on Scroll

The video game Doom famously would flash the screen red when you were hit. Chris Johnson not only took that idea, but incorporated a bunch of the UI from Doom into this tounge-in-cheek JavaScript library called Doom Scroller. Get it? Like, doom scrolling, but like, Doom scrolling. It’s funny, trust me.

I extracted bits from Chris’ cool project to focus on the damage animation itself. The red flash is done in HTML and CSS. First, we create a full screen overlay:

#doom-damage {   background-color: red;   position: fixed;   top: 0;   left: 0;   width: 100%;   height: 100%;   opacity: 0;   pointer-events: none; }

Note that it’s not display: none. It’s much harder to animate that as we have to wait until the animation is completed to apply it. That’s because display isn’t animatable. It’s doable, just annoying.

To flash it, we’ll apply a class that does it, but only temporarily.

const damage = document.getElementById("doom-damage");  function doomTakeDamage() {   damage.classList.add("do-damage");   setTimeout(function () {     damage.classList.remove("do-damage");   }, 400); }

When that class activates, we’ll immediately turn the screen red (really giving it that shock appeal) and then fade the red away:

.do-damage {   background-color: red;   animation: 0.4s doom-damage forwards; }  @keyframes doom-damage {   0% {     opacity: 1;   }   100% {     opacity: 0;   } }

The next bit calls the function that does the damage flash. Essentially it tracks the current scroll position, and if it’s past the nextDamagePosition, it will red flash and reset the next nextDamagePostition one full screen height length away.

If you want to see all that, I’ve abstracted it into this Pen:


The post Doom Damage Flash on Scroll appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , ,
[Top]

That’s Just How I Scroll

How do you know a page (or any element on that page) scrolls? Well, if it has a scrollbar, that’s a pretty good indication. You might still have to scrapple with your client about “the fold” or whatever, but I don’t think anyone is confused at what a scrollbar is or what it indicates.

But let’s say there is no scrollbar. That’s super common. macOS hides scrollbars by default and only shows them during scroll. Most mobile browsers don’t have scrollbars, even if you attempt to force them with something like overflow: scroll;.

Why does this matter? If you don’t know an area is scrollable, you might miss out on important content or functionality.

I regularly think about the Perfectly Cropped story from Tyler Hall. There is a screen on iOS that has important functionality you need to scroll down to, but there is no indicator whatsoever that you can scroll there.

The result of that was Tyler’s mom literally not being able to find functionality she was used to. Not great.

There is an elaborate way to detect visible scrollbars and force them to be visible, but something about that rubs me the wrong way. It doesn’t honor a user’s preference (assuming it is the user’s preference), requires DOM manipulation tests, and uses vendor-prefixed CSS (which will probably live a long time, but has been standardized now, so maybe not forever).

I enjoy these approaches and by Chris Smith and his thinking:

My favorite are the shadow-based techniques. To me an inset shadow is a really clear indicator, as it makes it appear that content is flowing underneath and the shadow follows an edge that as a hint that you can scroll in that direction. Plus, you’ve got CSS control there so I’d think it could match whatever UI situation you’re in fairly easily.

It should be known though that it can be done entirely in CSS though, no JavaScript, and is one of the great CSS tricks.


The post That’s Just How I Scroll appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, ,
[Top]

Memorize Scroll Position Across Page Loads

Hakim El Hattab tweeted a really nice little UX enhancement for a static site that includes a scrollable sidebar of navigation.

The trick is to throw the scroll position into localStorage right before the page is exited, and when loaded, grab that value and scroll to it. I’ll retype it from the tweet…

let sidebar = document.querySelector(".sidebar");  let top = localStorage.getItem("sidebar-scroll"); if (top !== null) {   sidebar.scrollTop = parseInt(top, 10); }  window.addEventListener("beforeunload", () => {   localStorage.setItem("sidebar-scroll", sidebar.scrollTop); });

What is surprising is that you don’t get a flash-of-wrong-scroll-position. I wonder why? Maybe it has to do with fancy paint holding stuff browsers are doing now? Not sure.

The post Memorize Scroll Position Across Page Loads appeared first on CSS-Tricks.

CSS-Tricks

, , , , ,
[Top]

An Overview of Scroll Technologies

Scroll-related animations have been used on the web for years. In recent years, they’ve started to become more common, perhaps in part due to devices being higher-performing and thus able to handle more animation. 

There are a number of scroll related technologies out there, so this article’s aim is to provide an overview of them and tools to help choose the one that’s right for you. I’d argue that these technologies can be broken down into two broad categories: ones for specific scroll-related behaviors and ones for more generic scroll-related behaviors.

Technologies for specific scroll-related behaviors

There are a few simple native CSS scroll effects that are supported by modern browsers. In some limited use cases they can be sufficient for your scroll animation needs.

position: sticky;

If all you need is for an element to stay in the same place on scroll for a portion of the page, using position: sticky is a good option. It’s straightforward and built into modern browsers. That said, a polyfill is required for IE support and some mobile browsers. For a solid overview, check out this article by Preethi.

CSS parallax

This isn’t a technology as much as a technique, but it’s pretty handy for simple parallax effects where you want different pieces of the page to move at different speeds on scroll. There’s a good write up of the technique on Alligator.io and a bunch of examples on CodePen, like this Firewatch header. The biggest downside for me is that it’s difficult to understand what values to use to set the perspective and transforms in order to get the parallax effect exactly right.

CSS scroll snap points

Scroll snap points allow the browser to snap to particular scroll positions that you set after a user is done with their normal scrolling. This can be helpful for keeping certain elements in view. However, the API is still in flux so be careful to use the most up to date API and be careful about relying on it in production. This CSS-Tricks article by Max Kohler is a good place to learn about it right now.

Smooth scrolling

Smooth scrolling is supported natively when jumping from section to section within a page using window.scrollTo() in JavaScript or even the scroll-behavior property in CSS. Generic smooth scrolling that smooths out mouse wheel actions is not supported natively in all browsers at this time. There are various JavaScript libraries that attempt to add smooth scroll support for the mousewheel action, but I’ve yet to find one that is bug-free and plays nicely with all other scroll technologies. Plus, smooth scrolling isn’t always good in the first place.

Technologies for generic scroll behaviors

Currently, there is no way to create or fire generic animations based on the scroll position using just CSS (though there is a proposal that could support some form of generic scroll based animations in CSS in the distant future) or to scrub through part of an animation. As such, if you want to animate elements on scroll, you’ll need to use at least some JavaScript to create the effect you want. There are two broad methods of using JavaScript to fire animations on scroll: using intersection observers and using the scroll event.

IntersectionObserver

Intersection observers are great if all you need for your animation is information related to whether or not and how much of an element is visible in the viewport. This makes them a good option for reveal animations. Even then, some things are difficult (though not impossible) using intersection observers, such as firing different animations depending on the direction an element enters the viewport. Intersection observers also aren’t very helpful if you want to do any scroll animations when an element is in between and not overlapping with the start and end points. 

Using the scroll event

Using the scroll event will give you the most freedom in controlling animations on scroll. It allows you to affect an element on scroll no matter where it is in terms of the viewport and set up starting and ending points exactly as you need for your project. 

With that being said, it can also be intense on performance if it isn’t throttled correctly and doesn’t have a convenient API to create particular behaviors. This is why it’s oftentimes helpful to use a good scrolling library that can handle the throttling for you and give you a more handy API to work with. Some can even handle a lot of the resizing issues for you!

Tools to create generic scroll behaviors

There are a few holistic scrolling libraries that attempt to give you full control over animations on scroll without you having to perform all of the calculations yourself. 

ScrollMagic

ScrollMagic provides a relatively simple API to create various effects on scroll and can be hooked into different animation libraries like GSAP and Velocity.js. However, it has become less maintained over the past few years, which lead to the creation of ScrollScene.

ScrollScene

ScrollScene is essentially a wrapper to try and make ScrollMagic and/or the intersection observer more usable. It uses a custom, more maintained version of ScrollMagic and adds additional features like video playback, scene init breakpoints, and scene duration breakpoints. It also makes use of GSAP

ScrollTrigger

ScrollTrigger is an official GreenSock plugin for GSAP. It a long list of features as the most easy to use API of any scroll library (at least to me). Using it, you can have complete control to define where your scroll animations start and end, animate anything (WebGL, canvas, SVG, DOM, whatever) on scroll, pin elements in place while the animation is running, and more. Plus it has the support of GreenSock and the GreenSock forums

Notable mention: Locomotive Scroll

While it doesn’t attempt to be as comprehensive of a scrolling library as the other libraries mentioned above, Locomotive Scroll is focused on providing custom smooth scrolling. You can also animate certain properties of DOM objects by adding data attributes or hook into the onscroll event to animate other types of objects. 

In summary

For some particular scroll animation effects, like sticky positioning and parallax, CSS technologies may be sufficient, at least when using a polyfill for browsers that don’t support those properties.

I generally recommend using GSAP’s ScrollTrigger because it can do everything that CSS properties can do, plus much more. ScrollTrigger will handle the browser support and calculations so that you can focus on animating!

Here’s a table covering which tools you can use to create particular effects:

position: sticky CSS parallax CSS scroll snap points Smooth Scrolling Intersection observers ScrollMagic ScrollScene Locomotive Scroll ScrollTrigger
Pinning ⚪️
Parallax effects
Scrubbing through animation with easing ⚪️ ⚪️ ⚪️ ⚪️ ⚪️
Snaps scroll position ⚪️ ⚪️ ⚪️ ⚪️
Dynamic Batching / Staggering
Supports horizontal scroll effects

Here’s a table comparing various other aspects of scroll technology:

position: sticky CSS parallax CSS scroll snap points Smooth scrolling Intersection observers ScrollMagic ScrollScene Locomotive Scroll ScrollTrigger
Usable in production (good browser support) ⚪️ ⚪️ ⚪️ ⚪️ ⚪️
Complete freedom in animation ⚪️
Maintained n/a n/a n/a n/a n/a
Works with DOM, Canvas, WebGl, SVG ⚪️
Works easily with resizing ⚪️
Restricts animation to relevant section ⚪️ ⚪️
Directionally aware ⚪️ ⚪️
Native technology
✅ = Yes
⚪️ = Partial support
❌ = No

The post An Overview of Scroll Technologies appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

How I Put the Scroll Percentage in the Browser Title Bar

Some nice trickery from Knut Melvær.

Ultimately the trick boils down to figuring out how far you’ve scrolled on the page and changing the title to show it, like:

document.title = `$  {percent}% $  {post.title}`

Knut’s trick assumes React and installing an additional library. I’m sure that library does all kinds of smart stuff, but if you’re looking to do this “vanilla” style, I’d probably rock something like this…

const percentLabel = document.querySelector("#percent"); const originalTitle = document.title;  window.addEventListener("scroll", () => {   let scrollTop = window.scrollY;   let docHeight = document.body.offsetHeight;   let winHeight = window.innerHeight;   let scrollPercent = scrollTop / (docHeight - winHeight);   let scrollPercentRounded = Math.round(scrollPercent * 100);   percentLabel.innerHTML = scrollPercentRounded;   document.title = `($  {scrollPercentRounded}%) $  {originalTitle}`; });

Here’s a project, and here’s the deployed site so you can see it in action.

Direct Link to ArticlePermalink

The post How I Put the Scroll Percentage in the Browser Title Bar appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

How to use CSS Scroll Snap

Nada Rifki demonstrates the scroll-snap-type and scroll-snap-alignCSS properties. I like that the demo shows that the items in the scrolling container can be different sizes. It is the edges of those children that matter, not some fixed snapping distance.

I like Max Kohler’s coverage as well, which includes a demo where the snapping can happen in multiple directions.

This is one of those things where, if you didn’t know about it, it’s worth a solid golf clap for CSS.

Direct Link to ArticlePermalink

The post How to use CSS Scroll Snap appeared first on CSS-Tricks.

CSS-Tricks

,
[Top]

Indicating Scroll Position on a Page With CSS

Scrolling is something we all know and do on the web to the extent that it’s an expectation or perhaps even a habit, like brushing our teeth. That’s probably why we don’t put too much thought into designing the scrolling experience — it’s a well-known basic function. In fact, the popular “there is no fold” saying comes from the idea that people know how to scroll and there is no arbitrary line that people don’t go under.

Scroll-based features tend to involve some bespoke concoction of CSS and JavaScript. That’s because there simply aren’t that many native features available to do it. But what if we could accomplish something that only uses CSS? 

Take this ingenious horizontal scrollbar with CSS, for instance. I want to do something similar, but to indicate scrolled sections rather than capture continuous scrolling. In other words, rather than increasing the length of the indicator during scroll, I only want to increase the length when a certain section of the page has been reached.

Like this:

Here’s my plan: Each section carries an indicator that’s undetectable until it reaches the top of the screen. That’s where it becomes visible by changing color and sticks to the top of the viewport.

The exact opposite should happen in reverse: the indicator will follow along when scrolling back up the screen, camouflaging itself back to being undetected to the naked eye.

There are two key parts to this. The first is for the indicator to change color when it’s near the top of the screen. The second is for the indicator to stay put at the top of the screen and come down only when its section is scrolled down to.

The second one is easy to do: we use position: sticky; on our elements. When a page is scrolled, a sticky element sticks to a given position on the screen within its parent container.

That brings us to changing colors. Since the background of an HTML document is white by default, I’m keeping white as the base color for the demo. This means the indicator should look white when it’s over the base color and turn to some other color when it’s over the indicator bar at the top of the screen.

The dashed indicator is currently invisible, but becomes visible when it sticks to the top and blends with the background color of the indicator container.

This is where CSS blend modes come into play. They give us so many options to create a variety of color amalgams. I’m going to go with the overlay value. This one is quite dynamic in nature. I won’t explain the blend in depth (because the CSS-Tricks Alamanac already does a good job of that) but taking this demo into account, I’ll say this: when the background color is white the resulting foreground color is white; and when the background is some other color, the resulting color is darker or lighter, depending on the color it’s mixed with.

The indicator stops in the demo are black. But, because of the blend, we see them as white because they are on a white background. And when they are over the indicator container element, which is a lovely shade of violet, we see a dark violet indicator stop, because we’re mixing the indicator stop’s black with the indicator container’s violet.

Starting with the HTML:

<div id="passageWrapper">   <strong>Sections Scrolled ↴</strong>   <!-- Indicator container -->   <div id="passage"></div> </div> 
 <!-- Indicator stop --> <div class=passageStops></div> 
 <!-- First Section --> <div class="sections">   <!-- Content --> </div> 
 <!-- Another indicator stop --> <div class="passageStops"></div> 
 <!-- Second Section --> <div class="sections">   <!-- Content --> </div> 
 <!-- Another indicator stop --> <div class="passageStops"></div> 
 <!-- Third Section --> <div class="sections">   <!-- Content --> </div>

Pretty straightforward, right? There’s a sticky container at the very top that holds the indicators when they reach the top.  From there, we have three sections of content, each one topped with an indicator that will stick to the top with the indicator and blend with it.

Here’s the CSS:

.passageStops {   background-color: black; /* Each indicator stop is black */   mix-blend-mode: overlay; /* This makes it appear white on a white background */   width: 33.3%; /* Three sections total, so each section is one-third */   top: calc(1em + 3px); } 
 #passage,  .passageStops{   height: 10px; } 
 #passageWrapper, .passageStops {   position: sticky; /* The container and stops should stick to the top */   z-index: 1; /* Make sure the indicator and stops stay at the forefront */ } 
 #passage {   background: violet; /* Will blend with black to make a darker violet indicator */   margin: 0 0 20px 0; } 
 #passageWrapper{   background-color: white; /* Make sure we're working with white to hide indicator stops */   height: 40px;   top: 0px; } 
 /* Each stop will shift one-third the width of the indicator container to cover the whole thing when the last section is reached. */ .passageStops:nth-child(4){ margin-left: 33.3%; } .passageStops:nth-child(6){ margin-left: 66.6%; } 
 /* More styling, blah blah. */

The indicators (.passageStops) are black. But the overlay blend mode makes them appear white when it blends with the white background under it. Since there are three sections, each indicator is of one-third width.

The indicators have position: sticky; with a top distance value. This means the indicators will stick once they reach the calculated position from the top of the screen. When that happens, the black indicators that appeared white blend with the violet indicator container, which makes them appear to be a dark violet, representing the new scroll position on the page.

The reverse is also true. When an indicator loses its sticky position, it will move from the violet background of the indicator bar to the white background of the page, hiding it once again… like it was never there!

Here’s the demo again:

That’s it. You can perhaps further experiment with this by having a non-white background with another blend mode, or a gradient for the indicator bar or stops.

The post Indicating Scroll Position on a Page With CSS appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]