Compile an efficient CSS Selector

Source: Internet
Author: User
ArticleDirectory
    • Modifier Selector
    • However
    • More efficient CSS selectors

Efficient CSS is no longer a new topic, nor a topic that I have to repeat, but it is a topic that I have always followed after working at Sky.

Many people forget or just don't realize that CSS can be efficient or possibly lead to low energy. However, we can ignore this situation when you think it will be too small to use inefficient CSS.

These rules are only applicable to websites with high performance requirements. These websites have high speed requirements. Any page may contain hundreds of DOM elements. But in practice, whether you are building the next Facebook or developing a local display page, it is always good to learn more ....

CSS Selector

CSS selectors are not new to most of us. The basic selectors are type (such as Div), ID (such as # header), and class (such as. Tweet ).

Unusual include basic pseudo-classes (such as hover) and more complex css3 and 'regex' selectors, such: first-childor [class ^ = "Grid-"].

The selector has inherent efficiency. If Steve Souders is referenced, the sequence of the CSS selector that is more effective to be less effective is as follows:

    1. ID, for example, # Header
    2. Class, such as. promo
    3. Type, such as Div
    4. Adjacent sibling, such as H2 + P
    5. Child, such as LI> ul
    6. Descendant, such as UL
    7. Universal, that is *
    8. Attribute, for example, [type = "text"]
    9. Pseudo-classes/-elements, such as a: hover

Reference even faster website from Steve Souders

It is important to know that although an ID is faster and better technically, it is rarely used. Using Steve Souders's CSS tester, we can find that an ID selector and a class selector differ very little in re-rendering speed.

In firefox6 on a Windows machine, I got the average Re-rendering data about a simple class selector. The ID selector provides an average value of 12.5, so it is actually slower than rendering a class.

The speed difference between IDs and classes is almost irrelevant.

The selection test for a type (<A>) provides a much slower re-rendering than a class or ID.

The test of a child selector with many layers gives a value of about 440!

Through this we can find that ids/classes and types/descendants are very different.

Note that these values vary greatly on different machines and browsers. I strongly recommend that you run it yourself.

 

Combination Selector

You can use a single standard selector, such as # Nav, to select all elements with "nav" as ID. You can also use a combination selector, such as # nav, to select any link element in the element with the ID of 'nav.

Now, we can read the combined tag from left to right. Find # nav first, and then find the elements in it. However, our browser does not parse these combinations from right to left.

When we see that # nav contains a, but the browser sees a in # Nav, these minor differences have a significant impact on the browser's performance, it is very valuable for colleagues to learn about them.

If you want to know why the browser resolves this issue, refer to this discussion on stack overflow.

For the browser, start from the rightmost element (the element that it wants to render) and go back to the DOM tree and choose to look down from the top level of the DOM tree, the rightmost selector (Key selector) is not even efficient.

This has a significant impact on the performance of CSS selectors ....

 

key selector

the key selector discussed here is the selector at the rightmost of a complex selector, it is also the first selector to be parsed by the browser.

let's go back to the beginning of the discussion. Which selector is the most efficient? Which selector is used as the key selector will affect the selector's performance. When we write CSS Code , this key selector affects the selector's efficiency.

A key selector is as follows:

 # content. intro {}

is a naturally efficient selector having higher performance? The browser searches for all instances of. Intro (the number is not large), and then looks up the DOM tree to determine whether the key selector is in the element with "content" as ID.

then, the performance of the following selectors is not very good:

# content * {}

This selector does this job, it first looks for each page (each page), and then checks whether they have a # Content parent element. This is a very inefficient selector because the execution overhead of its key selector is too large.

with this knowledge, we can make better choices when classifying and selecting elements.

Suppose we have a very huge page, a very large page, and a huge website. There are hundreds or even thousands of <A> labels. Social media links only occupy a small part and are contained in <ul> with the ID of # social. Suppose these links are Twitter, Facebook, dribble, and Google +. We have four social media links and hundreds of other links on this page.

The following selector is expensive and has poor performance:

# Social {}

The browser will visit thousands of links on the scan page, and then select the four links under the # social node. Our key selector matches a large number of tags that we are not interested in.

To eliminate this problem, we can specify a more explicit and explicit selector. Social-link for each <A> tag under the <ul> block of social media. But this is exactly the opposite of what we know. We know that when we use streamlined labels, we should try not to use redundant classes.

This is why I think performance is so interesting; there is a balance between the best practices of web pages and the speed.

We usually write as follows:

 
<Ul id = "social"> <li> <a href = "#" class = "Twitter"> Twitter </a> </LI> <li> <a href = "#" class = "Facebook"> Facebook </a> </LI> <li> <a href = "#" class = "dribble"> Dribbble </a> </LI> <li> <a href = "#" class = "gplus"> Google + </a> </LI> </ul>

CSS:

 
# Social {}

Now we change:

 
<Ul id = "social"> <li> <a href = "#" class = "social-link Twitter"> Twitter </a> </LI> <li> <a href = "#" class = "social-link Facebook"> Facebook </a> </LI> <li> <a href = "#" class = "social-Link dribble "> Dribbble </a> </LI> <li> <a href =" # "class =" social-link gplus "> Google + </a> </Li> </ul>

Corresponding CSS:

 
# Social. Social-link {}

This is a brand new key selector that matches fewer elements, meaning that the browser can find them faster and give them styles.

At the same time, we can actually further streamline the selector by using. Social-link {}, without the need for transition constraints. Read the next section for details.

So, in summary, one of your key selectors determines the workload of the browser, so you need to pay attention to it.

 

Modifier Selector

Now we have learned what the key selector is and it is the basis for subsequent work. Let's take a look at how to further optimize it. To use a more explicit key selector, you need to avoid over-using the modifier selector. Here is an over-modified selector:

1 Html body. Wrapper # Content {}

This option is too complex. At least three selectors are completely unnecessary. The simplified style should be:

 
# Content {}

So what?

This means that the browser needs to scan all the tags and check whether they contain a tag whose ID is "content", so that they can be searched continuously in HTML tags. This will cause the browser to do additional checks and is completely unnecessary. After knowing this, let's take a look at the following example:

 
# Nav Li {}

Simplified:

 
# Nav {}

We know that if label a is in the Li label and the Li label is in # Nav, we can remove Li from the selector. Then, because nav has an ID, which is unique, the elements it assigns are completely irrelevant. We can remove ul.

An excessively modified selector will cause the browser to do more work. Remove unnecessary parts from the selector to make your selector simpler and more efficient.

Are all these necessary?

The short answer is: Maybe not.

The longer answer is: it depends on the website you are creating. If you are working on your next work, go beyond the CSS selector performance to pursue clean code, because you don't really want to pay attention to it.

If you are creating the next version of Amazon, and the page speed changes in microseconds are indeed different, you may need it, but even so may not.

The browser will only get better and better in CSS parsing speed, even for mobile browsers. You may never notice the slow CSS selector in the browser,...

 

However

It is still happening, no matter how fast the browser is, they still have to do all the work we're talking about. Even if you don't even want to implement any of them, it is worth knowing. Remember that the selector may be costly, and you should avoid using a more costly selector wherever possible. It means that if you find yourself writing something such:

 
Div: Nth-of-type (3) UL: Last-Child Li: Nth-of-type (ODD) * {font-weight: bold}

Then you may not be able to do it. Now I am a newbie in the efficient selector world. If I miss something or you need to add something, please post it in the comments!

More efficient CSS selectors

How can I recommend Steve Souders's websites and books. It is enough for the extended reading you need. This guy knows a lot!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.