Ir para conteúdo

CSS level 4: custom selectors


Two dogs almost standing looking at the picture

The possibility to stock some values in variables was one of the main features among others, in my opinion, to the growth of the adoption of the pre-processor. What if we could store selectors? Yes, I will cry. ʘ‿ʘ

It is possible to do something like that:

@custom-selector :--button button, .btn, input[type="submit"];

:--button {
  /* css magic */ 

What we did was store all the elements button and input[type="submit"] and also every element with with btn class in :--button. Then, we declare the style rules in :--button.

Based on this, we can play a bit more and do something like:

@custom-selector :--enter :hover, :focus, .is-hover;
@custom-selector :--active :active, .is-active;

:--button:--enter {
  /* :hover, :focus and .is-hover styles */

:--button:--active {
  /* :active and .is-active styles */

What we did above was:

We could also get the same result using our friend matches:

:--button:matches(:hover, :focus, .is-hover) {
  /* :hover, :focus and .is-hover styles */

:--button:matches(:active, .is-active) {
  /* :active and .is-active styles */  

The difference, remembered by my friend Rafael Rinaldi is that our great custom selectors is a choice of preset compared with matches, which makes more easy to reuse.

See the Pen :not selector by Raphael Fabeni (@raphaelfabeni) on CodePen.

Here the link with the example above.

Do you like it? Did I write something stupid? Do you want to improve? Open an issue mentioning the post and let’s talk about it.

See all the posts