CSS selector priority

Source: Internet
Author: User

CSS priorities include four levels (intra-document selector, Id selector, class selector, and element selector) and the number of occurrences of each level. The CSS priority is calculated based on the number of occurrences of these four levels.

 

The CSS priority calculation rules are as follows:
* Set the style directly on the page, and Add 1, 0, 0, 0
* For each ID selector (for example, # ID), add 0, 1, 0, 0.
* Each class selector (such as. Class), each attribute selector (such as [attribute =]), and each pseudo class (such as: hover) plus
* Each element selector (such as P) or pseudo element selector (such as firstchild) is added with 0, 0, 1, and 1.
Then, accumulate the four numbers to obtain the priority value defined by each CSS,
Then compare the size from left to right, and the priority of CSS styles with large numbers is higher.

 

Example:
If defined in a CSS file or <style>:
1. H1 {color: red ;}
/* An element selector. The result is 0, 0, 1 */

2. Body H1 {color: green ;}
/* Two Element delimiters. The result is 0, 0, 0, 2 */

3. h2.grape {color: Purple ;}
/* An element selector and a class selector. The result is 0, 0 */

4. Li # answer {color: Navy ;}
/* An element selector and an ID selector. The result is 0, 1, 1 */

5. If the style attribute of an element is defined as follows: h1 {color: Blue ;}
/* Defined on the page. An element selector returns */

 

In this case, the H1 element is blue.

Note:
1 ,! The important declaration has the highest style priority. If a conflict occurs, the calculation is performed.
2. If the priorities are the same, select the final style.
3. The inherited style has the lowest priority.

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.