Home > Web Front-end > CSS Tutorial > How Can I Dynamically Adjust Text Color Based on Background Color Using CSS Gradients?

How Can I Dynamically Adjust Text Color Based on Background Color Using CSS Gradients?

Linda Hamilton
Release: 2024-12-08 19:58:12
Original
587 people have browsed it

How Can I Dynamically Adjust Text Color Based on Background Color Using CSS Gradients?

Text Color Adaption on Varying Backgrounds

In pursuit of a progress bar design, you seek to dynamically adjust the text color based on the underlying background hue. Specifically, you aim for black/dark-grey text over light backgrounds, black/dark-grey text over moderately light backgrounds, and white text over dark backgrounds.

Initial attempts using mix-blend-mode and other filters have proven unsuccessful in achieving your desired effect. However, a viable solution lies in employing an additional gradient for text coloring without relying on mix-blend mode.

Enhanced CSS Styling

Implement the following CSS code to achieve your desired text color adaptation:

.container {
  background: linear-gradient(to right, #43a047 50%, #eee 0);
  text-align: center;
}

.text {
  background: linear-gradient(to right, white 50%, black 0);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  -webkit-text-fill-color: transparent;
  font-weight: bold;
}
Copy after login

HTML Markup

Within the .container element, place your text content wrapped in a .text element:

<div class="container">
  <div class="text">Some text here</div>
</div>
Copy after login

Explanation

The additional gradient within .text establishes a gradient from white to black, with the transparent color set as the text fill. This allows the underlying background to blend with the text, resulting in the desired color adaptation effect.

The above is the detailed content of How Can I Dynamically Adjust Text Color Based on Background Color Using CSS Gradients?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template