Which one to select?

CSS Selectors

Selecting DOM elements is the most obvious thing to do in web development. The neat way to do so too. Not all interactions with a web page can be realised with alerts and prompts. The neat way is to make the user completely interact with the webpage. CSS selectors help in this.

Those identifiers with which particular style is applied to a particular DOM element are CSS selectors. CSS selectors identify a set of elements to which a set of CSS rules apply.

See this codepen for reference.

There are four basic categories of selectors: Basic, Grouping, Combinators, Pseudo.

The most efficient CSS selector is an ID selector. Since only one element has a unique ID, it has the highest matching quotient (HMQ) in the DOM.

Classes allow grouping of similar DOM elements. It has the second HMQ in DOM.

Types help in selecting similar tags in DOM. Selecting all elements under a given tagname in a DOM can be done via this.

Attribute selectors help in identifying those tags with the specified attribute value in the DOM.

Universal selector, (*), selects all the elements in the DOM.

From the above example, it is obvious that the ID selector style has more priority than the rest. Also, note that the styles in the bottom of the stylesheet overrides the styles in the above. (See the elements having a pointer as their cursor.) Of course, it depends on the hierarchy and the HQM of the element.

List selectors are used to select all the matching nodes.

In the above example, the ID and anchor tag matching elements are selected and styles are applied.

Descendants can be selected by giving a space between the parent and the descendant. Only those nodes get affected by the styles.

Children can be selected by the greater than symbol (>). Using this, direct children can be targeted.

The general sibling combinator (~) selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent.

The adjacent sibling combinator (+) selects adjacent siblings. This means that the second element directly follows the first, and both share the same parent.

The column combinator (||) selects nodes which belong to a column.

Pseudo classes are mainly based on the state of the DOM nodes. The anchor tag has multiple states : new link, visited, clicked, currently being visited etc. These can be represented as pseudo classes (:). Active, focus, hover are some of the most commonly used pseudo classes.

ID > Class > element > attribute > Universal
Inline Style > Style tag > Separate stylesheet
The lower rules in the stylesheet override those at the top.