This is not only a matter of style. It is a matter of performance and maintainability. Anecdotally, some selectors are difficult to implement efficiently for browsers. For example, the general sibling selector
A ~ B or the descendant selector
A B. And of course the universal selector
*. Unless actually needed, these should be avoided. The thing that is really fast is using class names or IDs. The comma
A, B is not considered a selector.
When you start out with CSS, you might be tempted to write something like
ul.#steps > li.item-without-bullet. That is not good for various reasons:
- Do not use IDs in selectors, because any ID can only be used once in a document. This prevents you from re-using the styling.
- Avoid element names in selectors. HTML is meant to be used as semantic markup that highlights what each element means. This should be kept mostly separate from the styling. You will still want to style elements directly (e.g. using a different font only for headings, or setting the line height for paragraphs). That is OK, and I wouldn't use classes for that (yuck), but you shouldn't refer to the element names when styling something special such as a nav bar, or an image carousel, or a pull quote, or ….
- Avoid ID and class names that focus too much on what text effect they provide (you might as well use inline style attributes), and instead use class names as custom elements or element modifiers, as a way to add your own semantics. A class such as
red-text is not as “semantic” as
- Avoid the descendant selector
A B and the child selector
A > B. You can usually encode the necessary information through your class names, e.g.
steps__step. You can trust that whoever is applying the classes to the HTML structure will respect proper nesting, given sufficiently self-documenting class names.
Seriously consider a strict naming scheme such as BEM (Block Element Modifier). Yes, it's incredible overkill, but using the BEM naming scheme can help you to properly structure your CSS. It exclusively uses class names, and does not generally use selectors.