Explain Codes LogoExplain Codes Logo

Fading out text on overflow with CSS if the text is bigger than allowed

html
responsive-design
css-gradients
web-development
Anton ShumikhinbyAnton Shumikhin·Dec 11, 2024
TLDR

Fade out text that overflows in a container by applying a CSS gradient on the container's :after pseudo-element. Specify overflow: hidden within the container, and color transition the linear-gradient from transparent to the container's background at the edge. Setup example:

.fade-text { position: relative; overflow: hidden; max-height: 100px; /* Defining a walkable horizon */ } .fade-text:after { content: ''; position: absolute; bottom: 0; /* Position the border patrol at exits */ width: 100%; /* Full width inspection */ height: 40px; /* Fade welcoming party */ background: linear-gradient(to bottom, rgba(255,255,255,0), #FFF); /* Fade from invisibility cloak to concrete wall */ }

Couple it with flooring HTML:

<div class="fade-text">Overflowing text that softly dissolves at the bottom. Magical ain't it?</div>

Critical dimmers are the height for the fade effect range, and background's rgba alpha & color to mingle seamlessly with your container.

Detailed explanation

Incorporating a fading effect in overflowing text employs CSS gradients and omits JavaScript. Let's dissect the working mechanism guided by key comparative pointers.

Understanding the gradient

The gradient factory in linear-gradient is instrumental, starting as the invisible man (thanks to transparent) and gradually suiting up to your container's background color.

Browser Compatibility Dance

To include everyone in the fade-out party, utilize CSS engine-dancer specific moves like -webkit-mask-image:

.fade-text:after { background: -webkit-linear-gradient(bottom, rgba(255,255,255,0) 60%, #FFF); /* DJ WebKit spinning the gradients */ background: linear-gradient(to bottom, rgba(255,255,255,0) 60%, #FFF); /* Chrome flexes his gradient move */ }

As CSS throws a universal party, your fade-out effect would feel inviting in nearly any browser your users sway on.

The fade zone secret

The marked dance floor with max-height or height on .fade-text reserves the exclusive corner for overflowing text. Further fade controls can be adjusted using the height on :after element:

.fade-text { max-height: 200px; /* Sky is not the limit */ } .fade-text:after { height: 60px; /* Control over disappearing act */ }

Positioning your pseudo-element: The game of thrones

The throne of the :after sits on top of the content court — seasoned by position: absolute; within a relative container — letting the text illusion to flow under the gradient mist.

Live playground examples

For real-time action, jsFiddle or CodePen serve as interactive playgrounds where tryouts are free and open, just like CSS!