首页 > 解决方案 > 为什么背景变黑但文本仍然是紫色(HTML CSS)?

问题描述

出于某种原因,当您将 CSS 选择器置于#div1 时,黑色背景会突然出现在 div 下的 p 标签上。如果我修复它并将选择器从 #div1 更改为 #div1 > h4 就像我的小教程文本解释的那样,它会自行修复。这是为什么?我只需要知道这是否是故障。谢谢!

请指教。谢谢。

body {
}

h2 {
     color: red;
}

p {
     color: pink;
}   

p {
    color: green;
}

p {
    color: purple;
}

.orange > p {
    color:orange;
}

.blue {
    color: blue;
}

#red {
    color: red;
}

#div1 > h4 {
    background-color: black;
    color: white;
}
<!DOCTYPE html>
<html>
<head>
    <title>CSS Basics</title>
    <link rel="stylesheet" type="text/css" href="basics.css">
</head>
<body>
    <p>This is the color purple not pink or green because CSS always takes the selector that is last in the cascade.</p>
    <div class="orange">
        <h1>This will not be orange</h1>
        <p>This will be orange because our selector in CSS for the class="orange" is like this: .orange > p making the h1 unchanged even though it is under the same class="orange" and the p will be the only one that changes to orange text!</p>
    </div>
    <p class="blue">This will be blue.</p>
    <p class="blue">This will also be blue, because you can use classes more than once unlike ID's.</p>
    <p id="red">This is an ID stating it is red.</p>
    <p id="red">This is using the same ID to say it is red, and as you can see it still works. But, be warned, using the same ID to multiple elements is invalid HTML and should be avoided!</p>
    <div id="div1">
        <p>This paragraph is wrapped in a div with the id of "div1" which gives a black background and white text.</p>
        <p>This paragraph is also wrapped in the div with the id of "div1". Notice that neither this paragraph or the paragraph before this one has white text or a black background. This is because we didn't specify in the selector to give p tags white text by using a > symbol between #div1 and p. In fact, it remained purple since that is the last thing applicable that the cascade found to work.</p>
        <h4>This h4 text on the other hand (which is also inside of the div as the other two paragraphs above it) works because we specified it to be #div1 > h4 for its selector. (side note: the two paragraphs above this h4 element do in fact get a black background until we write in #div > h4. I do not know why the text remains purple but the background changed to black...It fixed itself to not having a black background after we wrote in the code "#div1 > h4" so idk what to make of it...) 
        </h4>
    </div>
</body>
</html>

标签: htmlcsscss-selectors

解决方案


#div1 是 p 元素的元素。这意味着#div1 的某些属性(例如背景)将应用于子元素。但是,当您添加 > h4 时,它指定这些属性应仅适用于 #div1 元素的 h4 子元素。所以不,这不是一个小故障,而是有意的 CSS 行为。

需要注意的是,您有 3 个不同的 p {} 语句,每个语句都有不同的颜色...仅使用最后一个(因为它们都具有相同的特异性),您可以删除前两个。


推荐阅读