简体   繁体   English

CSS嵌套选择器

[英]CSS Nesting Selectors

In the below code, I am not understanding why we need to put color:white in a separate .marked p ? 在下面的代码中,我不明白为什么我们需要将color:white放在单独的.marked p Why it's not working if I do color:white within marked ? 如果我做color:white为什么它不起作用color:white marked color:white Can someone please explain? 有人可以解释一下吗? Thanks in advance! 提前致谢! :) :)

<!DOCTYPE html>
<html>
<head>
<style>
p
{
color:blue;
text-align:center;
}
.marked
{
background-color:red;
}
.marked p
{
color:white;
}
</style>
</head>

<body>
<p>This paragraph has blue text, and is center aligned.</p>
<div class="marked">
<p>This paragraph has not blue text.</p>
</div>
<p>p elements inside a "marked" classed element keeps the alignment style, but has a different text color.</p>
</body>
</html>

Normally a child element will inherit the color of its parent. 通常,子元素将继承其父元素的颜色。

However, in this case, you have specifically added a color style to all <p> elements: 但是,在这种情况下,您已经为所有<p>元素专门添加了一种颜色样式:

p { color:blue; text-align:center; }

That overrides any inherited styles that might have been set in .marked for this section of markup: 这将覆盖可能已在.marked中为此部分标记设置的任何继承样式:

<div class="marked">
    <p>This paragraph has not blue text.</p>
</div>

The selector: 选择器:

.marked p {}

has a higher specificity than the element selector p by itself and overrides its value. 具有比元素选择器p本身更高的特异性并覆盖其值。

You need to do that because the p selector has less specificity than .marked . 你需要这样做,因为p选择器的特异性低于.marked That's why you need to use .marked p in order to change the color. 这就是为什么你需要使用.marked p来改变颜色的原因。

You can learn about CSS specificity here: http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/ 您可以在此处了解CSS特异性: http//coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

Notice that text that isn't in a p tag will be blue. 请注意,不在p标记中的文本将为蓝色。 The fact that it's inside marked is irrelevant. 它内部marked的事实是无关紧要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM