简体   繁体   English

CSS2选择器和样式覆盖

[英]CSS2 Selectors and Style override

This is the HTML: 这是HTML:

<div id="testBlue">
    <span>hello</span>
    <span id="testGreen" class="testGreen">hello2</span>
</div>

If I have set in CSS: 如果我在CSS中设置:

#testBlue span { color:Blue; }    
.testGreen, #testGreen { color:Green; }

How can I override the general style in the second SPAN? 如何覆盖第二个SPAN中的常规样式?

I have tried both id and class selectors but it doesnt override it. 我已经尝试了id和类选择器,但它没有覆盖它。

In CSS, selectors with higher specificity override selectors that are more general. 在CSS中,具有更高特异性的选择器会覆盖更通用的选择器。

In your example you defined a style for a span inside a div with id = "testBlue" . 在您的示例中,您为div中span定义了一个样式,其id为“testBlue” This selector is more specific than the simple selector for the class or id testGreen , so it wins. 这个选择器比class或id testGreen的简单选择器更具体 ,因此它获胜。 You just need a selector more specific than #testBlue span , that is not difficult to find: 你只需要一个比#testBlue span更具体的选择器,这不难发现:

#testBlue span.testGreen {
    color: green;
}

Dont use important give it more weight like this 不要使用重要的给它更多的重量这样

#testBlue span { color:Blue; } 
#testblue #testgreen{color:Red}

Edit 编辑

Ive been taught using !important is bad practice 我已经被教过了!重要的是不好的做法

Certain objects in css have different weight in the decision to apply a rule css中的某些对象在决定应用规则时具有不同的权重

See http://htmldog.com/guides/cssadvanced/specificity/ http://htmldog.com/guides/cssadvanced/specificity/

I suppose its not wrong to use important but better practice to use weighting for specicifity 我认为使用重要但更好的做法来使用加权来进行特定处理并没有错

#testGreen { color: red !important;}

or 要么

.testGreen { color: red !important;}

Either will override the inherited rule, because !important puts more weight to one side of an an otherwise equal decision. 要么会覆盖继承的规则,因为!important会给一个平等的决定的一方增加权重。

span#testGreen
{
    color: green;
}

你可以使用选择器

#testBlue * { color:Blue; } 

You can also use the standard CSS DOM selectors (so you can drop the class names) like this: 你也可以使用标准的CSS DOM选择器(所以你可以删除类名),如下所示:

#testblue > span:first-child + span{}

testblue span THAT IS DIRECT DESCENDANT && FIRST-CHILD NEXT SIBLING span testblue span这是直接的下降&&第一个孩子下一个SIBLING跨度

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

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