Can CSS be used to dynamically change the color of an element based on a specific value?

Is it possible to dynamically change the background color of table cells using only CSS based on their values?

For example, I am looking to achieve a similar effect as in Excel with conditionally formatted values:

https://i.stack.imgur.com/6BsLB.png

If achievable, it would be fantastic to be able to smoothly transition between 2 or 3 different colors.

Answer №1

Definitely!

If you are open to utilizing CSS variables, it is completely feasible to create 2 or 3 color gradients.

You can employ CSS color-mix along with CSS variables to accomplish a color blend based on a variable value.

Simply utilize the following CSS:

.highlight-color {
  --min: 0;
  --max: 1;
  --incs: oklch;
  --value: 0.5;
  --high-color: #F8696B;
  --middle-color: #FFEB84;
  --low-color: #63BE7B;
}

.highlight-color .highlightme {
  /* This is where the magic happens */
  --normed: calc(100% * (var(--value) - var(--min))/(var(--max) - var(--min)));
}

.highlight-color.highlight-2color .highlightme {
  background-color: color-mix(
    in var(--incs),
    var(--high-color) var(--normed),
    var(--low-color)
  );
}

.highlight-color.highlight-3color .highlightme {
  --n1: calc((var(--normed) - 50%) * 2);
  --n2: calc(var(--normed)*2);
  background-color: color-mix(
    in var(--incs),
    color-mix(in var(--incs), var(--high-color) var(--n1), var(--middle-color)) var(--normed),
    color-mix(in var(--incs), var(--middle-color) var(--n2), var(--low-color))
  );
}

Next, include the following HTML:

<table>
    <tbody>
        <tr class="highlight-color highlight-3color" style="--min: 0; --max: 1;">
            <td class="highlightme" style="--value: 0.00;">0.00</td>
            
            <!-- other td elements here -->
          
            <td class="highlightme" style="--value: 1.00;">1.00</td>
        </tr>
    </tbody>
</table>

Upon executing this setup correctly, you will achieve the desired effect.

For automated setting of CSS values, consider using the provided Javascript snippet:

document.querySelectorAll('.autohighlight').forEach(el => {
    const values = [];
    const els = el.querySelectorAll('.highlightme');
    els.forEach(vel => {
        values.push(vel.innerText / 1);
        vel.style.setProperty('--value', vel.innerText / 1);
    });
    const max = Math.max(...values);
    const min = Math.min(...values);
    el.style.setProperty('--min', min);
    el.style.setProperty('--max', max);
});

To see this concept in action, check out an example codepen here.

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

Troubleshooting Issue with Absolute Positioning and Hover Effect on Material UI Button

I have a div containing a hidden button and an inner div filled with graphs and text. Occasionally, I need to blur the inner div and make the button float on top in the center of the blurred section, similar to the layout seen on subscription prompts found ...

Tips for maintaining a scrollable Material-UI Table with dynamic height?

I'm encountering an issue with the Material-UI Table component in terms of its size and scrollability. Summary: The Material-UI table only becomes scrollable when its parent has a fixed size. If I set the size to 100% to fit the parent, it overflows. ...

The CSS keyframe for mobile devices initiates from 100% and then proceeds to animate

Having some trouble with CSS animations on mobile devices. The animation works perfectly fine on desktop, but on mobile, it seems to display the final 100% keyframe first before animating from 0%. I've tried adding the initial style directly to the cl ...

Ways to enable JavaScript code to accept input from both a text field and a text

I have a JavaScript code that allows users to input text and choose to make it bold, italicized, or underlined. For example, if the user checks the bold option, the text will appear in bold format. Here is the JavaScript code I am using: $('input[n ...

Guide on adjusting image dimensions in JTextPane using HTML and CSS in the Java Swing environment

I am looking to add an image (such as a formula created from LaTeX) into JTextPane, using HTML+CSS for text formatting and manually setting its size. I attempted the following approach: import java.awt.Dimension; import javax.swing.JFrame; import javax.swi ...

Ways to insert a hyperlink within a div element

Consider the following HTML structure: <article id="1919"> <div class="entry-content clearfix"> <div></div> <div></div> </div> </article> &l ...

Display issue with ul and li elements in Safari browser causing menu to appear incorrectly

Although I am new to CSS, I managed to create a menu on my website that hovers over the background video successfully. It is a basic menu using a ul with li elements and it appears as intended in all browsers except Safari. In Safari, the menu items stack ...

Show the first letter of the first name using HTML

Is there a way to display the first letter of the first name followed by a period, a space, and then show the last name in asp/html/vb? ...

Utilizing AngularJS to display an array of user inputs

Hey there, hope all is well with you! I have been working on an HTML form that looks like this: <div class="table-responsive " > <table class="table table-bordered"> <tr ng-repeat="x in [1, 2, 3, 4, 5]"> <td> <td align="center" ...

What is the best way to display a div beneath the highlighted text within a textarea field?

I have encountered a situation where I want to display a div (like a popup) when text is selected in a text area. However, when using mouse-down for this action, the position of the div sometimes does not align directly below the selected text. Below is t ...

Ensure consistency in the heights of div elements, even when the images contained within have varying heights

I created a bootstrap webpage with a row of DIVs, each containing an image. As I resize the browser window, I noticed that the height of the first two DIVs remains consistent, but the third div's height varies because the image is only 50 pixels high. ...

Achieving priority for style.php over style.css

Having trouble with theme options overriding default CSS settings in style.css. Here's what I have in my header.php: <link rel='stylesheet' type='text/css' media='all' href="<?php bloginfo( 'stylesheet_url&apo ...

The PNG image keeps getting cropped

The bottom of a PNG image is being cropped off. View the picture illustrating the issue .loadMoreBtn-label { background-image: url(picture); background-repeat: no-repeat; padding-left: 30px; background-size: 23px 23px; background-posit ...

Unable to trigger a click on the submit button using JavaScript

I'm encountering difficulties in triggering a click using JavaScript on a Mailchimp pop-up subscribe form and I require your assistance. <!-- Title & Description - Holds HTML from CK editor --> <div class="content__titleDescripti ...

Tips to store Google fonts in the assets directory

I've included this link in my styles.scss @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap'); While it works locally, the API fails on production or is blocked. How can I host it within my p ...

Several iFrames embedded on the website automatically adjust to the same pre-set height

Apologies if this question has already been addressed, but I am struggling to properly articulate it. Here's the issue: I have a client's holiday accommodation website that uses three embedded iFrames for a Calendar, Booking Enquiry, and floorpla ...

Why is the child's CSS hover not functioning when the body has an event listener attached to it?

Check out the repository link here: https://codepen.io/Jaycethanks/pen/WNJqdWB I am trying to achieve a parallax effect on the body and image container, as well as a scale-up effect on images when hovered over. However, the hover functionality is not work ...

How can you utilize CSS to automatically generate section numbers, specifically for multiple sections?

Is it possible to automatically generate section numbering in CSS only when there are multiple sections present? I discovered that using CSS, one can create automatic numbering for sections. body { counter-reset: section } h2 { counter-reset: sub-section ...

Chromium CSS blend mode problem

Can anyone help me create a Photoshop overlay effect on my website? My code works perfectly in Firefox, but it's not functioning correctly in Chrome. Here's the demo. This is my current code: HTML <img src="http://lorempixel.com/output/fash ...

Exploring the process of assigning responses to questions within my software program

I am looking to display my question choices as radio buttons in a modal window. I have tried several solutions without success. Here is my question module: import questions from "./Data"; const QuestionModel = () => { return ( <div cl ...