CSS中权重的例子

  •   2009-07-31/13:28
  • CSS2.1中使用一个4位的数字来表示权重,以下是有关权重的一些规定:
    类型选择符的权重为:0001
    类选择符的权重为:0010
    通用选择符的权重为:0000
    子选择符的权重为:0000
    属性选择符的权重为:0010
    伪类选择符的权重为:0010
    伪元素选择符的权重为:0010
    包含选择符的权重为:包含的选择符权重值之和
    内联样式的权重为:1000
    继承的样式的权重为:0000
    <!--例子1-->

    <html>
    <head>
    <title>样式冲突</title>
    <style type="text/css">
    <!--
      p{color:red}              /*权重为:0001*/
      p[align]{color:blue}    /*权重为:0010*/
      .vip{color:green}       /*权重为:0010*/
      #myid{color:purple}   /*权重为:0100*/
    -->
    </style>
    </head>

    <body>
     
      p{color:red}              权重为:0001<br/>
      p[align]{color:blue}    权重为:0010<br/>
      .vip{color:green}       权重为:0010<br/>
      #myid{color:purple}   权重为:0100<br/>

     <p>p{color:red}</p>
     <p class="vip" id="myid">#myid{color:purple}</p>
     <p align="left" class="vip" >.vip{color:green}</p>
     类和属性两者权重相同,但为什么会应用类样式而不是属性样式,
    </body>

    </html>

     

    <!--例子-2-->

    <!--权重可以累加-->

    <html>
    <head>
    <style type="text/css">
    <!--
    p{color:red}
    body p{color:green}
    -->
    </style>
    </head>

    <body>
    <p>body p{color:green}</p>
    为什么会应用body p{color:green}样式,而不是p{color:red}样式呢?
    因为body p{color:green}==body权重 +  p权重 ==2 > p{color:red}==1
    </body>

    </html>

     

    <!--例子-3-->

    <!--内联样式的权重为1000,大于内部样式和外部样式的权重,因此当样式冲突时,只会显示内联样式-->

    <html>
    <head>
    <style type="text/css">
    <!--
    p{color:red}
    -->
    </style>
    </head>

    <body>
    <p style="color:green">It's green</p>
    </body>

    </html>

     

    <!--例子-4-->
    <!--!mportant-->
    <html>
    <head>
    <style type="text/css">
    <!--
    body{font-size:20pt; color:blue;}
    div{text-decoration:underline !important; font-size=:10pt; color:red !important;}
    .vip{text-decoration:overline; font-size:30pt; color:green}
    #other{color:black}
    p{color:yellow}
    -->
    </style>
    </head>

    <body>
    body中的文字
    <div class="vip">
        class="vip",div中的文字
        <p>p中的文字,p位于div中</p>
    </div>
    <div id="other">
        id="other",另一个div中的文字
    </div>
    <br/>虽然类型选择器div的权重要比类选择器.vip和.other要小,但如果在div的样式之后加上!important,
    则表示在div标签文本(不包括div标签中的标签,因为它们具有可继承性),该样式具有最高权重。
    </body>

    </html>


    评论 {{userinfo.comments}}

    {{money}}

    {{question.question}}

    A {{question.A}}
    B {{question.B}}
    C {{question.C}}
    D {{question.D}}
    提交

    驱动号 更多