Skip navigation
CSS Trick 📜 You can trigger text highlights on scroll with scroll-driven animations 😎 mark {…
0:00 / 0:36

CSS Trick 📜 You can trigger text highlights on scroll with scroll-driven animations 😎 mark {…

jhey ʕ•ᴥ•ʔ

@jh3yy149K followers

Visit on X
2,387 likesDownloadOriginal post

208,593 views

CSS Trick 📜 You can trigger text highlights on scroll with scroll-driven animations 😎 mark { animation: highlight; animation-timeline: view(); } @​keyframes highlight { to { --lit: 1; }} mark span { background-position: calc(var(--lit) * -110%) 0; transition: background 1s; } The trick is using a scroll-driven animation to flip a custom property on a element 🎚️ You flip the value between 0 and 1, and that transitions the background position of the element mark { --lit: 0; animation: highlight steps(1) both; animation-timeline: view(); animation-range: entry 100% cover 10%; } The background has to be applied on a child of the mark to see the change in the custom property 👀 mark span { background: linear-gradient( 120deg, yellow 50%, transparent 50%) 110% 0 / 220% 100% no-repeat; background-position: calc(var(--lit) * 110%) 0; transition: background-position 1s; } The trick is to set the background-size so that it's bigger than the element and then split the background-color in the middle using a linear-gradient 🤙 And the property flips fills in the color 🫶 That's it! If there isn't support for scroll-driven animations, use JavaScript's IntersectionObserver API. The code for this is in the demo 😎 Cool example of using CSS as an IntersectionObserver! CodePen.IO link below 👇

10 Comments

Comments from the original post on X (Twitter)

  • jhey ▲🐻🎈's profile picture

    @jh3yy

    Here's that @CodePen link 🫶 Should be good in all browsers 🤙 No CSS scroll animation support? Falls back to Intersection observer ✨

    65 likes

  • Arif Sardar's profile picture

    @NeuroNexul

    Indeed I like the way you toggle the theme much more than the highlight.

    9 likes

  • jhey ▲🐻🎈's profile picture

    @jh3yy

    @Code_With_Arif Teaser for the next demo/video coming up 🫶😎

    5 likes

  • Ryan's profile picture

    @ryan92801

    Codepen link?

    2 likes

  • tsúbomi's profile picture

    @josh_kolawole

    this makes reading easy for users.

    1 like

  • Aryan's profile picture

    @IAmAryan_A

    This is some. crazy CSS love it

    1 like

  • Madat Bayramov's profile picture

    @madatbay

    Really wish X to add possibility to have code snippet in the posts. Readability is a way too low in such posts

    1 like

  • Andre Specht's profile picture

    @andrespecht

    Are scroll-driven events available on the main browsers?

    1 like

  • An Vo's profile picture

    @anvodev

    @HienHuuPham Amazing

    1 like

  • ed's profile picture

    @edimoldovan

    Would love to see a codepen link on this. Any chance you can share, please?