"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Invert CSS Font Color Based on Background Color?

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

Published on 2024-12-22
Browse:197

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%;
}

Using Two DIVs

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

.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%;
}

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3