Css – Use CSS to dynamically calculate the forground color based on the inherited background color

background-colorcolorscss

We are changing the look and feel of our website. The colors of many elements are changing. Our secondary button is changing from a purple background with white text:

To a red border surrounding an inherited background:

We use this button in hundreds of locations on many pages. It resides in sections with various background colors (and a few background images).

With the old button treatment, I didn't have to worry about the background color when determining the text color. The text color was always white:

.secondary-button {
    color: white;
}

Now the font color is going to have to change based on the background. It either needs to be white or purple depending on how dark the background is. The white just doesn't work on light colored backgrounds:

Because this button is used in so many places, I don't want to have to manually go through all of them and choose on a per button basis. Is there a way in CSS to choose one of two background colors based on the darkness of the background? Something like:

.secondary-button {
    color: calc(background-color>#999?purple:white);
}

I found ways to accomplish this with JavaScript: Change text color based on brightness of the covered background area? and also language agnostic algorithms to calculate how dark a color is: Determine font color based on background color but I was unable to locate a pure CSS solution.

Best Solution

It's an alternative approach, but you could use a dark (albeit translucent to some degree) text-shadow which would highlight the button's text on lighter backgrounds and be more or less imperceptible on darker backgrounds.

Eg. text-shadow: 1px 1px rgba(0,0,0,0.5), -1px 1px rgba(0,0,0,0.5), 1px -1px rgba(0,0,0,0.5), -1px -1px rgba(0,0,0,0.5);

Example:

div {
display: inline-block;
width: 280px;
height: 50px;
padding: 45px 5px;
}

div:nth-of-type(1) {
background-color: rgb(70,41,126);
}

div:nth-of-type(2) {
background-color: rgb(235,240,244);
}

.secondary-button {
width: 280px;
height: 50px;
color: white;
font-size: 18px;
font-weight: bold;
text-transform: uppercase;
text-shadow: 1px 1px rgba(0,0,0,0.5), -1px 1px rgba(0,0,0,0.5), 1px -1px rgba(0,0,0,0.5), -1px -1px rgba(0,0,0,0.5);
background-color: transparent;
border: 4px solid rgb(245,69,86);
border-radius: 15px 15px 15px 0;
}
<div>
<button type="button" class="secondary-button">Play the Demo</button>
</div>

<div>
<button type="button" class="secondary-button">Play the Demo</button>
</div>

Related Question