代码之家  ›  专栏  ›  技术社区  ›  Robert Claypool

CSS继承:重写作为子代选择器的父选择器

  •  7
  • Robert Claypool  · 技术社区  · 15 年前

    如何使此链接在不更改或删除父选择器的情况下使用子选择器?(我希望链接为蓝色。)

    <html>
        <head>
            <style>
                .parent a { color:Red; }
                .child { color:Blue; }
            </style>
        </head>
        <body>
            <div class="parent">
                <a class="child" href="http://www.stackoverflow.com">
                    stackoverflow
                </a>
            </div>
        </body>
    </html>
    

    在这种情况下,家长会凌驾于孩子之上,这让我感到惊讶!

    3 回复  |  直到 12 年前
        1
  •  9
  •   AxelEckenberger    15 年前

    使用 a.child 作为选择器。

    <html>
        <head>
            <style>
                .parent a { color:Red; }
                a.child { color:Blue; }
            </style>
        </head>
        <body>
            <div class="parent">
                <a class="child" href="http://www.stackoverflow.com">
                    stackoverflow
                </a>
            </div>
        </body>
    </html>
    
        2
  •  8
  •   Scott Cranfill    15 年前

    这是由于CSS的特殊性。额外的 a 之后 .parent 使其更具体 亲本 相应地,比刚才更具体 .child . Obalix的建议为选择器提供了相同的特性,既有一个基本的HTML元素,也有一个类名称。当专一性相等时,它将应用层次结构中指定的最深值,正如您所期望的那样。

    本文(以及链接到的资源)很好地解释了CSS的特殊性: http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

        3
  •  4
  •   Giedrius    12 年前

    为将来的探索 http://css-tricks.com/specifics-on-css-specificity/

    基本上,您可以按此顺序计算选择器值

    Inline | ID | Class/pseudoclass | Element
    1      | 1  | 1                 | 1
    

    其中inline=1000,id=100,class=10,element=1

    在你的情况下 .parent a == 11 .child == 10 这就是父元素重写子元素样式的原因。