Multiple CSS Classes

If you ever have used a theme or script, you will often see an element with various classes attached to that element; such as '<div class-="red black">'. As you may have already expected, the element makes reference to the red and black classes.

That is the easiest part while applying the style to the element is only a little more involved. If the single element contains 2 classes, how is the style interpreted from the stylesheet? To make this a little more clear, add the code below to the final stylesheet.

As you can see below, the element can access all 3 colors. But, the priority is top down for the single classes while the reference using .black.red takes precedence. Thus, the actual color of the text is blue even if you moved .black.red to the top. But, if you deleted .black.red and shuffled the order for .red and .black you will see that color will change to reflect the last single class.

<style>    
    .black{color:black}
    .red{color:red} 
    .black.red{color:blue}  
</style>

<div class="red black">My Text</div>

 

Now, try the code below. As you can see, the color is now red, because red overrides black and the use of !important will stick unless it is overridden by another !important.

<style>
    .black{color:black}
    .red{color:red !important}
    .black.red{color:blue}
</style>

<div class="red black">My Text</div>

 

Finally, try the code below. As you can see, the color is blue as you may have expected.

<style>
    .black{color:black}
    .red{color:red !important}
    .black.red{color: blue !important}
</style>

<div class="red black">My Text</div>

 

Now, for one little twist. Move the .black.red above .black so it looks the block below. As you can see, .black.red !important overrides anything below. Also, if you had the same order without !important, the text color would be blue too.

<style>
    .black.red{color: blue !important}
    .black{color:black}
    .red{color:red !important}    
</style>

<div class="red black">My Text</div>