Creating state-selectors in utility-first CSS

Posted on

Libraries like Tailwind CSS provide prefixes like hover: or focus: to style pseudo-selectors. A class of hover:bg-red-500 will only turn a background red when hovering over an element, for example.

We can do the same by adding the pseudo-class both to the beginning and end of our selector. Escaping the first colon also makes it part of the selector’s name.

<style>
  .focus\:yellow:focus {
    background: yellow;
  }
 
  .hover\:orange:hover {
    background: orange;
  }
</style>
 
<button class="focus:yellow hover:orange">
  Yellow on focus, orange on hover
</button>
<style>
  .focus\:yellow:focus {
    background: yellow;
  }
 
  .hover\:orange:hover {
    background: orange;
  }
</style>
 
<button class="focus:yellow hover:orange">
  Yellow on focus, orange on hover
</button>
Debug
none
Grid overlay