Create a fade-in/out effect at the edges of a carousel with Tailwind
The Context
Building the homepage of my current website, I wanted to have a carousel component which showed some books I like. See my homepage for the end result!
The Problem
I started by assuming I could create a fade effect similar to how you can create a background which fades between different colours, however I knew this wasn’t the full solution, and was struggling to articulate to google what I was looking for.
The Solution
In the end, I achieved the effect by targeting the
before
and after
pseudo-elements in the containing div
which can be done with the tailwind before:
and after:
selectors. I used the classnames library to manage adding classes to my elements.I added
bg-gradient-to-r
to the before
and bg-gradient-to-l
to the after
element. After this I added dark:from-gray-900 from-white to-transparent
to get the fade effect for both light and dark mode and added z-10
to the elements to bring them above the other elements in the div (making the obscured by the transparent fade).I added
pointer-events-none
to both to prevent the before
and after
elements registering any clicks or hover eventsAs the elements scrolled along the carousel, it now seems like they fade in and out of the page.
The Code
<div className={classnames( "relative flex overflow-x-hidden pb-4", "before:bg-gradient-to-r before:z-10 before:absolute before:w-24 before:top-0 before:bottom-0 before:pointer-events-none", "after:bg-gradient-to-l after:z-10 after:absolute after:w-24 after:top-0 after:bottom-0 after:right-0 after:pointer-events-none", "dark:from-gray-900 from-white to-transparent" )}> </div>