How to make text fade using CSS gradients top and bottom?

I am trying to create a fade effect for a paragraph from both the top and bottom. However, I am only able to achieve the fade effect from either the top or the bottom.

HTML:

<p className="bottom-overflow-fade">
  {content}
</p>

CSS:

.bottom-overflow-fade {
  mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
  -webkit-mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
}

.top-overflow-fade {
  mask-image: linear-gradient(to top, black 80%, transparent 100%);
  -webkit-mask-image: linear-gradient(to top, black 80%, transparent 100%);
}

Current Result:

https://i.sstatic.net/74y6X.png

Issue:

Combining both of these classnames in the paragraph does not result in the desired fade effect. Using either one separately works perfectly for fading from either the top or bottom. Is it possible to merge both CSS properties into one to achieve a fade effect from both the top and bottom?

Note: This question is not related to any form of animation.

Answer №1

The reason behind this behavior lies in the nature of CSS. When two declarations for the same property are applied, only one will take precedence. To achieve a gradient effect that starts transparent, goes to black, and ends transparent, you can create a single class with the following code:

.top-bottom-overflow-fade {
  mask-image: linear-gradient(transparent, black 20%, black 80%, transparent 100%);
  -webkit-mask-image: linear-gradient(transparent, black 20%, black 80%, transparent 100%);
}

UPDATE

In response to a question about the values passed to the linear-gradient function, here is an explanation:

  1. The first argument is optional and determines the direction of the gradient. This can be specified using keywords like to left top or angles such as deg, turn, rad, or grad. The default direction is top to bottom if no value is provided.
  2. The subsequent arguments consist of colors and optional color stops. These color stops define where each color should start and stop. Adding more color stops results in narrower bands of color transitions. To create abrupt color transitions, set the stopping percentage of one color to match the starting percentage of the next color. CSS gradients can be used creatively to produce intricate patterns by stacking multiple images using the background-image property!

Answer №2

For those seeking a versatile solution that includes top, bottom, and both fading effects.

The key is to utilize a mask created with three gradients - initially set in white color (no transparency) and then adjust the CSS variable to achieve the desired fading effect.

.fade {
  -webkit-mask:
    linear-gradient(to top   ,#fff,var(--t,#fff)) top    / 100% 30%,
    linear-gradient(#fff,#fff)                    center / 100% 40%,
    linear-gradient(to bottom,#fff,var(--b,#fff)) bottom / 100% 30%;
  -webkit-mask-repeat:no-repeat;
  mask:
    linear-gradient(to top   ,#fff,var(--t,#fff)) top    / 100% 30%,
    linear-gradient(#fff,#fff)                    center / 100% 40%,
    linear-gradient(to bottom,#fff,var(--b,#fff)) bottom / 100% 30%;
  mask-repeat:no-repeat;
}

.top {
  --t:transparent;
}

.bottom {
  --b:transparent;
}

p {
 font-size:25px;
 max-width:180px;
 display:inline-block;
}
<p class="fade top">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras euismod est quis nibh porta, ut vehicula magna imperdiet. Etiam euismod urna id venenatis pulvinar
</p>

<p class="fade bottom">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras euismod est quis nibh porta, ut vehicula magna imperdiet. Etiam euismod urna id venenatis pulvinar
</p>

<p class="fade top bottom">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras euismod est quis nibh porta, ut vehicula magna imperdiet. Etiam euismod urna id venenatis pulvinar
</p>

To further illustrate this technique, here's the same code applied as a background:

.fade {
  background:
    linear-gradient(to top   ,red,var(--t,green))   top    / 100% 30%,
    linear-gradient(pink,pink)                      center / 100% 40%,
    linear-gradient(to bottom,blue,var(--b,purple)) bottom / 100% 30%;
  background-repeat:no-repeat;
}

.top {
  --t:transparent;
}

.bottom {
  --b:transparent;
}

p {
 font-size:25px;
 max-width:180px;
 display:inline-block;
}
<p class="fade top">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras euismod est quis nibh porta, ut vehicula magna imperdiet. Etiam euismod urna id venenatis pulvinar
</p>

<p class="fade bottom">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras euismod est quis nibh porta, ut vehicula magna imperdiet. Etiam euismod urna id venenatis pulvinar
</p>

<p class="fade top bottom">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras euismod est quis nibh porta, ut vehicula magna imperdiet. Etiam euismod urna id venenatis pulvinar
</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error occurred during the file watch process in PhpStorm after saving the CSSO file

Following the advice in the official PhpStorm documentation, I have implemented a CSS minifier. However, upon attempting to use it, I encountered the following error: cmd.exe /D /C call C:\Users\douglas\AppData\Roaming\npm\css ...

Exchange information between two selected items

Below is a simplified version of the current code that I am working with: https://jsfiddle.net/2zauty83/8/ Javascript function checkboxlimit(checkgroup) { var checkgroup = checkgroup for (var i = 0; i < checkgroup.length; i++) { checkgroup[i] ...

Two vertical divs stacked on top of each other, each expanding to the entire height and width of the browser window

Is there a way to set the width and height of two divs on a webpage to match the dimensions of the browser window, requiring scrolling to view the second div? In addition, how can I ensure that the content within these divs is vertically centered? To ach ...

Understanding how to access and interpret comments within the HTML DOM body using Selenium操作

I am attempting to extract the following comment from the body of an HTML DOM using Selenium: <html> <head class=.....> <body> <script>...</script> <!-- Campaign Name: POC_SITE_MONETIZATION_DEALS_QA Experience Name: SMBelo ...

Gaps separating frames

<!Doctype html> <html> <frameset rows="26%,24%,*" noresize border="0" frameborder="no" framespacing="0"> <frame src="frame_a.html" target="_self" name="logo" scrolling="auto"> <frame src="frame_b.html" target="_self" name="menu" ...

Step-by-step guide to accessing a PDF file stored locally using Angular2 and HTML5

I am attempting to access a .pdf file in local storage using an iFrame. Here is the code I have tried: In HTML file <object [data]="sanitizer.bypassSecurityTrustResourceUrl(selectedItem.FilePath)" type="application/pdf"> <iframe [src]="sanitizer ...

Creating a popup window using HTML

I am attempting to create a pop-up window using HTML, but I'm struggling to get it to appear in the desired way. My goal is this: to have a pop-up show up when the profile image is clicked on. Here's the HTML <span class="profile"><im ...

Page for Calling with jQuery Mobile

How can I navigate to the administrator page while also refreshing the page? The concept is: If the user logs in successfully, the page will automatically redirect to the administrator page using HTML5 storage for data. For example: sessionStorage.setIte ...

What is the process for including a JavaScript file in an HTML document?

Greetings to all and thank you for taking the time! I have a straightforward query for you.. I have designed an html page featuring only a basemap (open street map). Moreover, I possess a javascript file which utilizes your coordinates to calculate a perce ...

Unable to change the color of the tab indicator

Hello, I am currently using materializecss in conjunction with Angular 6. Just to clarify, I am solely utilizing the materializecss library and not ng2-materialize. My issue arises when attempting to customize the tab indicator background color by modifyi ...

How can I trigger a function by clicking on a link that was generated dynamically with jQuery?

I am dynamically creating multiple <a href="#"></a> elements with dynamically assigned id attributes like <a href="#" id='delete"+id+"'></a>. The IDs generated will be like delete01, delete02, .... I want to trigger a func ...

Implement JQuery UI Accordion to enhance navigation on mobile devices

I am implementing the JQuery UI Accordion to expand content on a website. Below is the basic markup structure: <div class="accordion"> <h2>Heading</h2> <div>Content</div> <h2>Heading</h2> <div& ...

Tips for transmitting one or multiple data using jquery.ajax

I found this code on stackoverflow and it is working well for uploading multiple files. However, I am facing an issue where I cannot send additional parameters along with the file upload. Despite trying various methods, I have been unsuccessful in sending ...

Is it possible to maintain child divs in a single line?

Despite trying numerous recommendations (many involving white-space:nowrap and display:inline-block), I have been unsuccessful in keeping these child divs on a single line with horizontal scrolling. This is my code: <div id="list"> < ...

How to change the padding of a parent element in CSS3?

I've created a circle-shaped div element using the following code: #circle{ width: 320px; height: 320px; background-image: url('image.jpg'); border-radius: 50%; background-position: 50% 50%; transition: all 1s; } This circle expands on hov ...

Disabling buttons in a Fiori UI5 application using HTML: A step-by-step guide

I don't have much experience with scripting languages. I am attempting to hide buttons within a SAP Fiori app by using the "Inspect element" tool in the Mozilla browser. When I delete the HTML code, the button disappears, but I would like to accomplis ...

The background-image property fails to display on a table element

I’m having trouble displaying a background image in a table within my Django app. Here’s the code I’m using: <table style="background-image: url('/static/assets/img/myimage.png') ;background-position: 0 100% !important;background-repeat ...

CSS DROP DOWN NAVIGATION MENU - Struggling to maintain hover effect on main menu item while navigating through sub-menu

I am facing a challenge with a CSS-only drop-down menu where the top main menu item loses its highlight when I move the cursor over the sub-menu items. You can view the menu in action here: . For example, if you hover over "Kids" and then move your cursor ...

Controlling z-buffering for transparent textures in Three.js

Creating a simple map with flat, paper-like trees protruding from it in WebGL using THREE.js has been quite a challenge. The issue lies in understanding how the library handles z-buffering. Despite numerous attempts to tweak parameters like renderer.sortOb ...

What are the methods to ascertain whether an HTML element possesses a pseudo element?

Is there a method to identify whether an HTML element has a pseudo element (::before / ::after) applied to it without invoking the function: window.getComputedStyle(element, ":before/:after"); MODIFIED: the response is NEGATIVE The issue with getCompute ...