The key lies in using CSS selectors efficiently to maximize performance and minimize load time, though this efficient usage matters only for website with thousands of DOM elements and the speed is the key for the existence in the market.
A CSS selector selects the HTML element(s) you want to style. CSS selectors are used to “find” (or select) the HTML elements you want to style.
We can divide CSS selectors into five categories:
- Simple selectors (select elements based on name, id, class)
- Combinator selectors (select elements based on a specific relationship between them)
- Pseudo-class selectors (select elements based on a certain state)
- Pseudo-elements selectors (select and style a part of an element)
- Attribute selectors (select elements based on an attribute or attribute value)
Selects all elements. Optionally, it may be restricted to a specific namespace or to all namespaces.
* will match all the elements of the document.
Selects all elements that have the given node name.
input will match any
Selects all elements that have the given
.index will match any element that has a class of “index”.
Selects an element based on the value of its
id attribute. There should be only one element with a given ID in a document.
#toc will match the element that has the ID “toc”.
Selects all elements that have the given attribute.
[autoplay] will match all elements that have the
autoplay attribute set (to any value).
, selector is a grouping method that selects all the matching nodes.
div, span will match both
The ” ” (space) combinator selects nodes that are descendants of the first element.
div span will match all
<span> elements that are inside a
> combinator selects nodes that are direct children of the first element.
A > B
ul > li will match all
<li> elements that are nested directly inside a
General sibling combinator
~ combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent.
A ~ B
p ~ span will match all
<span> elements that follow a
<p>, immediately or not.
Adjacent sibling combinator
+ combinator matches the second element only if it immediately follows the first element.
A + B
h2 + p will match all
<p> elements that immediately follow an
|| combinator selects nodes which belong to a column.
A || B
col || td will match all
<td> elements that belong to the scope of the
: pseudo allow the selection of elements based on state information that is not contained in the document tree.
a:visited will match all
<a> elements that have been visited by the user.
:: pseudo represent entities that are not included in HTML.
p::first-line will match the first line of all