Recommended: css video tutorial
.class
The selector is higher than the label selector. The #id
selector is higher than the .class
selector. !important
attribute has the highest weight value priority, greater than all selectors. Let us enter the practice of which one has higher priority between the tag selector and the .class
selector. The practical content is as follows : Set the text color of the h2
tag in the HTML
page.
Code block
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>优先级</title> <style> h2{ color: red; /*红色*/ } .box{ color: springgreen; /*绿色*/ } </style> </head> <body> <h2 class="box">微笑是最初的信仰</h2> </body> </html>
Result graph
Let’s enter.class
selector and id
selector, which one has higher priority? Practice, the practice content is such as: setting the h2
tag in the HTML
page Text color.
Code block
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>优先级</title> <style> h2{ color: red; /*红色*/ } .box{ color: springgreen; /*绿色*/ } #box{ color:blue; /*蓝色*/ } </style> </head> <body> <h2 class="box" id="box">微笑是最初的信仰</h2> </body> </html>
Result graph
Now we know the tag selector priority The lowest level, so I added the !important
attribute to the tag selector. Who has a higher priority?
!important weight usage format is as follows:
color: red !important; /*红色*/
Note: Attribute: value !important
Attribute values can be separated by spaces.
Let's get into the !important
attribute usage practice and see how powerful the !important
attribute is.
Code block
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>!important使用</title> <style> h2{ color: red !important; /*红色*/ } .box{ color: springgreen; /*绿色*/ } #box{ color:blue; /*蓝色*/ } </style> </head> <body> <h2 class="box" id="box">微笑是最初的信仰</h2> </body> </html>
Result graph
Priority from low to high such as: tag selector , .class
selector, #id
selector, !important
attribute
For more programming-related knowledge, please visit: Programming teaching! !
The above is the detailed content of Understand CSS selector priority and !important weight. For more information, please follow other related articles on the PHP Chinese website!