Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using Pure CSS to Access and Style Span Content

I’m working with a dynamic data table, and I need the text color in the availability column to change dynamically depending on the package status from a generic database. Specifically, I want "In Stock" to be green and "Out of Stock" to be red. Here’s a simplified version of the HTML structure:

<div class="fd-datatable">
    <div class="innerScrollContainer">
        <div class="row" role="row" tabindex="0" aria-rowindex="1" aria-label="row">
            <div aria-colindex="1" role="gridcell">
                <!-- ... other columns ... -->
                <div aria-colindex="4" role="gridcell">
                    <span>In Stock</span>
                </div>
                <!-- ... other columns ... -->
            </div>
        </div>
        <!-- ... other rows ... -->
    </div>
</div>

How can I access the text within the tag, for each row so that I can change its color, using only CSS?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You cannot do this but here is a little hack to achieve what you want. It relies on the fact that both text won’t take the same width so I will use the size as a condition to apply a different coloration.

Here is a simplified example. The 90px is what control the condition, you need to adjust it based on you real code

span {
  display: inline-block;
  font-size: 20px;
  color: #0000;
  background: 
    linear-gradient(green 0 0) 0/calc(90px - 100%) 1%,
    linear-gradient(red   0 0) 0/calc(100% - 90px) 1%;
  -webkit-background-clip: text;
          background-clip: text;
}
<span>In Stock</span>
<span>Out of Stock</span>
<span>Out of Stock</span>
<span>In Stock</span>

I have detailed article where I explain such a trick and more: https://css-tricks.com/responsive-layouts-fewer-media-queries/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading