Sachin Jain
Sachin Jain

Reputation: 21842

Efficient CSS selector

I know we should avoid using CSS descendant selectors but I was just wondering which of these two is more efficient and why ?

#myDiv .childDiv .grandchildAnchor span

or

#myDiv > .childDiv > .grandchildAnchor > span  

You can assume both are valid for my markup. How should I test for such kind of things. Is there an online platform where I can write both versions of my code and it will fetch me results in terms of efficiency.

EDIT: I want to learn these things.

Upvotes: 2

Views: 587

Answers (4)

Mayo
Mayo

Reputation: 379

According to Mozilla there is a clear-cut answer: 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.

Frequently, what is really desired is the child selector. For instance, the performances are so bad, that descendant selectors are banned in Firefox' User Interface CSS, without a specific justification. It's a good idea to do the same on your Web pages

BAD
treehead treerow treecell {…}

BETTER, BUT STILL BAD (see next guideline)
treehead > treerow > treecell {…}

You can find the above quote and more at: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 60037

Just use ids. Then you can have the benefit in automated testing see QTP

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179264

If you're planning your CSS selectors around which ones are more efficient, you're focusing on the wrong issue.

Don't be penny wise and pound foolish.

It takes an absolutely massive amount of HTML and CSS to slow down a browser in any meaningful way, so rather than focusing on which selector is more efficient, focus on which selector is appropriate. You'll save more in performance by compressing your images, minifying your CSS and JS, or simply removing a single image from the page.

In your example, neither selector is appropriate and neither is efficient. Unless you have a very good reason to nest selections, your CSS should be optimized to be:

//specificity 0-0-1-0
.some-span-type {
    ...
}

It's possible that you may need to check if the span is in a particular type of container, in which case you might want to use:

//specificity 0-0-2-0
.some-container .some-span-type {
    ...
}

It's also possible that you may need to check if the span is within a unique container, in which case you might want to use:

//specificity 0-1-1-0
#some-container .some-span-type {
    ...
}

The issue is that once you start adding more styles with two or three selectors, you'll quickly find that you'll need three or four or five selectors to style subsequent elements to properly override the existing styles.

Upvotes: 4

Related Questions