基于父div的CSS优先级 [英] CSS precedence based on parent div

查看:119
本文介绍了基于父div的CSS优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在浏览器中查看以下代码,则链接显示为红色。我希望它是绿色的,因为辅助div嵌套在主要div内。看起来颜色是由css文件中元素的顺序决定的。如果我将.secondary移到.primary之后,则链接为绿色。

If you view the following code in a browser the link appears red. I would expect it to be green because the secondary div is nested inside the primary div. It appears the color is determined by the order of the elements in the css file. If I move .secondary after .primary the link is green.

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <style>
        .secondary a {
            color: green;
        }

        .primary a {
            color: red;
        }
    </style>
</head>
<body>
    <div class="primary">
        <div class="secondary">
            <a href="http://www.google.com">test</a>
        </div>
    </div>
</body>
</html>

除了更改文件顺序之外,如何使链接尊重其父div的颜色?

Other than changing the order in the file how can I make the link respect the color from its parent div?

编辑:这是一个非常简单的示例。实际上,在初级和次级类之间可能还有许多其他div标签。

This is a very simplified example. In practice there could be many other div tags between the primary and secondary classes.

链接到codepen

推荐答案

问题是两个选择器具有相同的特异性。 CSS唯一知道与相同选择器有关的事情是选择最新的选择器。

The issue is that the two selector have the same specificity. The only thing that CSS knows to do with selectors of the same specificity is to choose the most recent one

因此,您需要使孩子的特殊性超过首先,一种方法是放入

Thus, you need to make the specificity of the child more than the firsts, one way is to put

.primary .secondary a {
    color:green;
}

另一种方法是在类之外添加元素类型

Another way would be to put the element type in addition to the class

这就是为什么使用正确的格式来将CSS构造为HTML布局的页面的原因,而父母要先于孩子

This is the reason why it is proper formatting to structure your CSS as the page it is laid out in the HTML, with parents coming before children

有关如何确定特异性的更多信息,请在此处检查

For more information as to how specificity is determined, check here

这篇关于基于父div的CSS优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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