CSS Selectors

Selectors simply refer to the HTML elements to which CSS rules apply; they’re what is actually being “selected” for each rule.

Universal Selector

It selects elements of any/all type, hence the name “universal”, and the syntax for it is a simple asterisk.

Type Selectors

A type selector will select all elements of the given type, and the syntax is just the name of the element.

Class Selectors

Class selectors will select all elements with the given class, which is just an attribute you place on an HTML element. The syntax for a class selector is a period immediately followed by the case-sensitive value of the class attribute. Also, you can add multiple classes to a single element as a space-separated list.

ID Selectors

IDs are similar to classes, the syntax is a hashtag immediately followed by the case-sensitive value of the ID attribute. The major difference between classes and IDs is that an element can only have one ID, you should use IDs sparingly (if at all).

Grouping Selectors

What if we have two groups of elements that share some of their style declarations? To cut down on the repetition, we can group these two selectors together as a comma-separated list.

Parent and Sibling Combinators

Some more ways we can access different elements:

  • > - the child combinator
  • + - the adjacent sibling combinator
  • ~ - the general sibling combinator

Pseudo-classes

These include "Dynamic and User Action Pseudo-classes" such as :focus, :hover, :active etc. which make your page feel more dynamic and interactive. "Structural pseudo-classes" are a powerful way to select elements based on their position within the DOM. A few examples are- :root, :first-child, :last-child, :nth-child.

Attribute Selectors

This is a slightly more flexible way of selecting elements by targeting specific attributes and/or their values. Few examples- [attribute], selector[attribute], [attribute="value"].