Style Sheet Snacks: Create a Fading Scrollable Element in pure CSS

Welcome to the 2nd installment if Style Sheet Snacks! This week, we’re going to show two ways of creating a scrollable element that fades out as the user scrolls. This could be used for any div with a scrolling overflow!

While there are more ways to achieve this using javascript, we are going to focus on pure css solutions.  

Method #1: Using Box Shadow

One method that certainly works for creating a “fading” effect on scrollable elements is to add an absolutely-positioned element with a box shadow in order to give the effect of the text fading out.

This method works wonderful with elements that have a background that is a single color, or no background.  It also has good support on older browsers which makes it a good choice if you can use it.   

In order to achieve the effect, you need to add an element with a box shadow attribute that is a linear gradient.  If you want to refresh on gradients, check out our last style sheet snack on the gradients here.  The gradient should range from 0 to 1 in opacity and use the color thats identical to the background of your element.

See the Pen Box Shadow Fade Effect by The Datababe (@Thedatababe) on CodePen.

Method #2: Using mask

While the above method works well across a number of browsers, it does not work well if you have a background image and you’d simply like text to become transparent towards the bottom of the element. For this reason, I much prefer using mask-image to create beautiful, scrolling divs that fade. However, it should be noted that this is not supported on older browsers,

This method is also a bit less code. Instead of using an absolutely positioned fade-out element, we can wrap our scrollable section in a container, and apply mask-image with a linear-gradient in order to fade out the text. Take a look at the codepen below to see how it works in action.

See the Pen Mask Fade Effect by The Datababe (@Thedatababe) on CodePen.

Conclusion

While both of these methods work on in certain situations, I always prefer webkit-mask because it is less code to write, and is an elegant solution that truly makes the text fade instead of covering the element with another in order to achieve the effect.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>