CSS选择器权重计算和优化规则

1.CSS优先级:

!important > 行内样式 > ID选择器 > class选择器 || 属性选择器 > 标签选择器 > 通配符*

2.复杂嵌套中css样式权重的计算:

权重计算规则(下文数字均为虚拟数字,便于计算,并非真实数值)

  1. 行内(内联)样式:style="", 权重 1000;
  2. ID选择器,权重 100;
  3. 类、伪类、属性选择器,权重10;
  4. 标签选择器、类型选择器、伪元素选择器,如div p,权重1;
  5. 通配符、子选择器、相邻选择器,如*、>、+,权重 0;

计算示例:

​
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <style>
        #username{/*权重:100*1=100*/
            font-size: 14px;
            color: #333333;
        }
        #users_info #username{/*权重:100*2=200*/
            font-size: 15px;
            color: #1B6D85;
        }
        #users_info a{/*权重:100*1+1=101*/
            font-size: 16px;
            color: #398439;
        }
        .user_info #username{/*权重:100*1+10*1=110*/
            font-size: 17px;
            color: #66512C;
        }
        .user_info a{/*权重:10*1+1*1=11*/
            font-size: 18px;
            color: #843534;
        }
        #in_block .user_info #username{/*权重:100*2+10*1=210*/
            font-size: 19px;
            color: #8A6D3B;
        }
        .contain #in_block .user_info #username{/*权重:100*2+10*2=220*/
            font-size: 20px;
            color: #C7254E;
        }
        #content #in_block .user_info a{/*权重:100*2+10*1+1*1=211*/
            font-size: 21px;
            color: #F0AD4E;
        }
    </style>
    <body>
        <div class="contain" id="content" style="width: 200px;height: 200px;margin: 0 auto;background: #C4E3F3;">
            <div id="in_block" class="left_content">
                <div class="user_info" id="users_info">
                    <a id="username">注意我的字体大小和颜色</a>
                </div>
            </div>
        </div>
    </body>
</html>
 
 
​

猜你喜欢

转载自blog.csdn.net/RedaTao/article/details/107405759