Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS multiple child selectors vs single tag selector performance

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?

like image 316
Gerard Reches Avatar asked Apr 27 '16 15:04

Gerard Reches


1 Answers

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.

like image 53
Shaggy Avatar answered Sep 24 '22 14:09

Shaggy