When creating content we often want our dynamic content to be styled according to the underlying data.  This is fairly easy to accomplish by adding a few elements to your style sheet, preparing your HTML output and some simple additions to your PHP code.

Let’s take a look at this sample data:

ID Data 1 Data 2
1 Value 0
Value 1
Value A
2 Value 1
Value 1
Value B

In this example, we want to highlight Value 0 and Value 1 with different colors that will be determined by the value.  In our HTML we’ll start be ensuring that each value is output surrounded by a <span> tag.

<table>
<tbody>
<thead>
<tr>
<th>ID</th>
<th>Data 1</th>
<th>Data 2</th>
</tr>
</thead>
<tr>
<td>1</td>
<td><span>Value <?php echo $first_value; ?></span> <span>Value <?php echo $second_value; ?></span></td>
<td>Value A</td>
</tr>
<tr>
<td>2</td>
<td><span>Value <?php echo $first_value; ?></span> <span>Value <?php echo $second_value; ?></span></td>
<td>Value B</td>
</tr>
</tbody>
</table>

The <span> tags are used to isolate the items and makes it possible to apply styling to inline text.  In our span tags we’ll add a class attribute with a unique prefix and add our custom dynamic value to the end within the PHP code..

<table>
<tbody>
<thead>
<tr>
<th>ID</th>
<th>Data 1</th>
<th>Data 2</th>
</tr>
</thead>
<tr>
<td>1</td>
<td><span class="hightlight_<?php echo $first_value; ?>">Value <?php echo $first_value; ?></span> <span class="hightlight_<?php echo $second_value; ?>">Value <?php echo $second_value; ?></span></td>
<td>Value A</td>
</tr>
<tr>
<td>2</td>
<td><span class="hightlight_<?php echo $first_value; ?>">Value <?php echo $first_value; ?></span> <span class="hightlight_<?php echo $second_value; ?>">Value <?php echo $second_value; ?></span></td>
<td>Value B</td>
</tr>
</tbody>
</table>

Lastly, we’ll add some CSS to our style sheet.

<style>
     .highlight_0 {
          background-color:  rgba(54, 255, 0, 0.15);
     }
     .highlight_1 {
          background-color:  rgba(255, 0, 97, 0.15);
     }
</style>

The dynamically generated class will have the respective style applied to it. For example, class=”hightlight_<?php echo $first_value; ?>” when the value of $first_value is 0 will output hightlight_0.  This technique can be used for any dynamic values that have a consistence pattern.  However, if your values are more robust, such as street addresses, you probably won’t be able to create every possible scenario.

It is also important to note that your values cannot have any spaces or special characters.  hightlight_red wine, for instance, will not work well.

That’s it.  You should now have dynamically styled data.

ID Data 1 Data 2
1 Value 0
Value 1
Value A
2 Value 1
Value 1
Value B