需要帮助了解CSS选择性规则 [英] Need help understanding CSS selectivity rules

查看:126
本文介绍了需要帮助了解CSS选择性规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<html><head><style type="text/css">
    #foo  { color: blue; }
    a.bar { color: red; }
    #foo .baz  { background-color: cyan; }
    a.bar > .baz { background-color: yellow; }
</style></head>
<body>
    <div id="foo">
        <a href="#" class="bar">
            <span class="baz">TEXT</span>
        </a>
    </div>
</body>
</html>

我是一个CSS的noob,但我的直觉告诉我 bar < span> 包含 TEXT c $ c> #foo ,并且 TEXT 应显示为红色,带有黄色背景。或者如果 #foo 更具体,则 TEXT 应为带有青色背景的蓝色。

I'm a CSS noob, but my intuition tells me that a.bar is a more specific match for the <span> containing TEXT than #foo, and that TEXT should appear in red with a yellow background. Or if #foo is more specific, then TEXT should be in blue with a cyan background.

但是, TEXT 会显示为红色,带有青色背景。如何 a.bar #foo 更具体,但 #foo。 baz 更具体。a.bar> .baz ?我将如何得到这个文本以红色和青色黄色显示最少的中断(最小的更改集)到我已经指定的样式?

Instead, TEXT appears (as tested on Chrome, IE8) in red with a cyan background. How is it that a.bar is more specific than #foo, but #foo .baz is more specific than a.bar > .baz? How would I get this text to appear with red and cyan yellow with the least disruption (smallest set of changes) to the styles I have already specified?

推荐答案

您看到的文字颜色与应用选择器无关。两个选择器正在应用,但是应用于不同的元素。转换为内联样式的CSS将如下所示:

What you're seeing with the text color doesn't have to do with which selector is applied. Both selectors are being applied, but to different elements. Translated to inline styles your CSS would look like:

<body>
    <div id="foo" style="color: blue;">
        <a href="#" class="bar" style="color: red;">
            <span class="baz" style="background-color: cyan;">TEXT</span>
        </a>
    </div>
</body>

background-color:yellow; 由更具体的选择器,但您的其他选择器不会相互覆盖。它们适用于不同的元素。跨度将从其最接近的祖先继承颜色 c>,该祖先具有 color 的指定值。在这种情况下是< a>

background-color: yellow; was overridden by the more specific selector, but your other selectors don't override each other. They apply to different elements. The span will inherit the color from it's closest ancestor which has a specified value for color. In this case that is the <a>.

如果你想要一个黄色的背景,建议通过在 #foo 之前加上 #foo a.bar> .baz 。这是 JSFiddle演示

If you want a yellow background with minimal changes I would suggest making that selector have higher specificity by prepending #foo onto it like #foo a.bar > .baz. Here is a JSFiddle demo.

这篇关于需要帮助了解CSS选择性规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆