Home >Web Front-end >HTML Tutorial >CSS selector priority and efficiency optimization_html/css_WEB-ITnose
CSS selector priority and efficiency optimization
Date: 7th of Aug, 2015
Author: HaoyCn
This article collects information about CSS selection from all over the Internet Summarize the article on the device and summarize one by yourself.
above Among the selectors, in addition, tested
attribute selector = pseudo-class selector (apply the last one)
:last-child{color:red;}[desc]{color:green;}
pseudo-class selector> adjacent selector
:last-child{color:green;}p ~ p{color:blue;}
Adjacent selector = child selector = descendant selector (last one applied)
p~p{color:red;}body p{color:blue;}body > p{color:green;}
descendant selector> tag selector
p ~ p{color:blue;}p{color:green;}
c9ccee2e6ea535a969eb3f532ad9fe89531ac245ce3e4fe3d50054a55f265927 is the same as 439940bdb518e9fd892bed955b59e35a, and the application depends on the order of the c9ccee2e6ea535a969eb3f532ad9fe89 tag and the 439940bdb518e9fd892bed955b59e35a tag
Element The priority of the attribute is higher than the above two styles
!important The priority is higher than the above two styles
Remarks
!important BUG in IE6: In the same group of CSS properties, !important does not work. For example:
#selector{color:blue !important;color:green;}
The principle of reading selectors is from right to left. Therefore, the last selector on the right we write is called the key selector and has a decisive impact on efficiency.
The following efficiency rankings are provided by @Steve Souders.
Higher priority may not necessarily be more efficient
For example: #id .class and div#id p.class
The former is more efficient than the latter, and the latter has a higher priority than the former. We need to balance efficiency with prioritization.
Many suggestions are provided at the following URL:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficie ...
A brief summary is as follows:
Avoid using wildcards
Do not use tag names or class names to modify IDs Rules: If the rule uses an ID selector as the key selector, do not add a tag name to the rule. Because the ID itself is unique, adding tag names will unnecessarily reduce matching efficiency.
Do not use tag names to modify classes: Compared to tags, classes are more unique.
Try to be as specific as possible: the simplest and crudest cause of inefficiency is using too many rules on tags. Adding classes to elements can be subdivided into classes more quickly and can reduce the time it takes for rules to match tags.
About descendant selectors and sub-selectors: Avoid using descendant selectors. If you must use them, it is recommended to use sub-selectors instead. However, sub-selectors should also be used with caution. Tag rules should never be used. Contains child selectors.
Take advantage of inheritability: there is no need to declare styles on general content.