Here, we have a simple React application that renders a div with some content that is being styled by a CSS class generated using TypeStyle. We can easily make the div red by passing in a style object to the style function.
In addition to CSS property names, the style object also takes a $nest property, which allows you to style arbitrary child selectors. Every key in $nest is considered a selector. Any $ in the selector will be replaced by the generated class name.
This allows us to use $:hover to add styles specific to the hover pseudo-class. As an example, we will simply bump up the font size to 50 pixels when you hover over the div. Now, when we hover over the div with our mouse, you can see that it works as expected.
It is always fun and super easy to add a CSS transition for the properties you are going to change in different pseudo-classes. Over here, I'm simply adding a transition for the font size property, as that is the property that I'm going to change. With this transition in place, even our excessively exaggerated property change feels much more smooth.
One thing worth pointing out is encapsulation of pseudo-class styles under the class name, which results in more maintainable CSS. You can add styles for as many pseudo-classes as you need using different keys under the nest property.
To demonstrate that, let's go ahead and change a div to a button so that it supports the focus pseudo-class. We will go ahead and add a selector for the focus class, and within its style object, we will bump up the font size to 30 pixels. You can see that if I tab into the button to give it focus, the font size bumps up. If I tab away, it goes down. If I hover over the button, it gets a nice, big font size of 50 pixels, which goes back if I hover away.
One interesting to note is that both hover and focus are changing the font size, so there are bound to be conflicts. If I click the button to focus it, the focus style works fine, but while it is focused, hover styles do not work. This is because the focus style is winning over the hover style.
If you want to ensure that hover always takes precedence over focus, you can do that by simply adding another dollar in your nested selector. Now, if we tab to the button to focus it, and then hover over it, the hover styles take precedence. There isn't any TypeStyle magic here. This works simply because, in CSS, repeated class names increase CSS specificity, so the first selector takes precedence over the second one.
One final thing worth mentioning is that it's conventional to write selectors in increasing order of significance if it matters. We will go ahead and move hover down.