Theoretically CSS child selectors are more efficient than tag selectors. But what happens when you have a class and you need to style a specific tags inside this class element but they aren't a first level child?
Let's see an example:
.styled-table > tbody > tr > td{
// Some cell styles
}
VS
.styled-table td{
// Some cell styles
}
Which of these is a better CSS performance practice?
Per MDN: Avoid the descendant selector.~
The descendant selector is the most expensive selector in CSS. It is dreadfully expensive—especially if the selector is in the Tag or Universal Category.
If you think it through logically, with a descendant selector, the CSS engine will check each child of the parent element (in this case .styled-table
) looking for matches (in this case the td
tag) and then each child of those children and so on and so forth.
With a child selector, though, you're telling the engine exactly which "path" to follow to look for a match. If it fails to find a match at any point in the path (e.g., if your .styled-table
does not have a tbody
as one of its immediate children) then it will abandon the selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With