Search code examples
htmlcsscss-selectorssemanticspseudo-class

Best semantic for pseudo-class


Im want to know the best semantic for an element that already have a class and then change the style with the pseudo-class.

The case is for an "a" element.

a.btn {...}

a:hover.btn {...} or a.btn:hover {...}

Wich one is the best practice?


Solution

  • Bearing in mind selectors resolve right to left, you should use a.btn:hover simply for the fact it is (should always be) the case only a single item is hovered at a time, making the selector most efficient in initial identification. Once the hovered item is selected, it is checked whether it has the class btn then is an a. If all btn elements are a, you could simply to .btn:hover for greater efficiency.

    By doing a:hover.btn the selector is identifying all elements with the class btn first, then finding the one that is hovered.

    With that said- in CSS classes and pseudo selectors have the same weighting. As such the realisable difference will be negligible, if any.

    As far as semantics is concerned, it generally makes more sense when reading CSS to have a.btn:hover - e.g. a elements with the btn class which are hovered. Also, dont forget the element and class are part of your HTML, so when scanning your CSS these appear together making identifying effected elements easier.