Search code examples
csspseudo-classreadability

Where to put CSS pseudo classes?


There are several tips about writing better CSS on the Internet, like sorting properties alphabetical for example, but no one has mentioned about pseudo classes' best practice, e.g.

nav ul {
  /*main styles*/
}
nav ul:hover li.selected {
  background-color: transparent;
}
nav ul li {
  /*main styles*/
}
nav ul li:hover {
  background: #ffaacc;
}

You may think that It's not necessary at all (well It actually Isn't In the above code) , but I found It important to have a certain way for that and It will be important when you have a CSS file with more than 1000 lines and considering all major CSS pseudo classes (such as :link :hover :active :focus :blur :visited etc)

Where should I put pseudo classes?

Should I put them in a separate place (end of file or even another specific file)?

Should I just put them right bellow their default selector ?


Solution

  • Include them directly after the elements default selector as required. I typically order pseudo classes from a user interaction perspective, someone hovers over the link before they make it active so order it that way etc.

    For example a link css:

    • Element CSS
    • :link
    • :visited (moved forward so :hover and :active can override it)
    • :hover
    • :active