Home > Web Front-end > CSS Tutorial > How Can I Invert CSS Font Color Based on Background Color?

How Can I Invert CSS Font Color Based on Background Color?

Barbara Streisand
Release: 2024-12-17 15:25:20
Original
538 people have browsed it

How Can I Invert CSS Font Color Based on Background Color?

Invert CSS Font Color Based on Background Color

In CSS, there is no direct property that allows you to invert the font color based on the background color. However, there are various techniques you can utilize to achieve this effect.

Using Pseudo Elements

Pseudo-elements can be used to create a wrapper around the text, which you can then style independently. For example:

.inverted-bar {
    position: relative;
}

.inverted-bar:before,
.inverted-bar:after {
    padding: 10px 0;
    text-indent: 10px;
    position: absolute;
    white-space: nowrap;
    overflow: hidden;
    content: attr(data-content);
}

.inverted-bar:before {
    background-color: aqua;
    color: red;
    width: 100%;
}

.inverted-bar:after {
    background-color: red;
    color: aqua;
    width: 20%;
}
Copy after login

Using Two DIVs

For older browsers that do not support pseudo-elements, you can use two DIVs instead:

<div class="inverted-bar" data-content="Lorem ipsum dolor sit amet"></div>
Copy after login
.inverted-bar {
    position: relative;
    padding: 10px;
    text-indent: 10px;
}

.inverted-bar:before {
    content: attr(data-content);
    background-color: aqua;
    color: red;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    white-space: nowrap;
    overflow: hidden;
    padding: 10px 0;
    width: 100%;
}

.inverted-bar > div {
    content: attr(data-content);
    background-color: red;
    color: aqua;
    position: absolute;
    padding: 10px 0;
    top: 0;
    left: 0;
    width: 20%;
}
Copy after login

Note: The exact implementation may vary depending on your specific requirements and browser support.

The above is the detailed content of How Can I Invert CSS Font Color Based on Background Color?. 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