覆盖 CSS 中的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6295321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:44:21  来源:igfitidea点击:

Overriding properties in CSS

css

提问by de3

#iddiv span {
    display: inline-block;
    width: 190px;
}
.myclass {
    width:10px;
}

Then I have

然后我有

<div id="iddiv">
    <span>hello:</span> 
    <span class="myclass">yeah</span> <br/>
</div>

I would like the first span's widthto be 190px, and second's to be 10px. But both are 190px: why it's not overriding the widthpropoerty?

我想第一spanwidth是190px,和第二的是10px的。但两者都是 190px:为什么它不覆盖width属性?

EDIT: Thanks for your responses. What about unsetting width? I don't want 10px width, just default width as if it was undefined

编辑:感谢您的回复。取消设置宽度怎么样?我不想要 10px 宽度,只是默认宽度,好像它是未定义的

采纳答案by RwwL

Because id+selector (#iddiv span) is more specific than a class. Either

因为 id+selector (#iddiv span) 比类更具体。任何一个

#iddiv span.myclass

or

或者

#iddiv .myclass

should work for this case.

应该适用于这种情况。

Learn more about CSS specificity hereor by Googling it.

在此处或通过谷歌搜索了解有关 CSS 特异性的更多信息。

回答by Eric

You could always use the !importantflag to override:

您始终可以使用该!important标志来覆盖:

.myclass {
    width: 10px !important;
}

回答by JohnP

CSS applies styles according to the specificity of the selectors

CSS 根据选择器的特殊性应用样式

#iddiv spanis more specific than myclass. Changing it to #iddiv .myclassshould fix the issue for you.

#iddiv span比 更具体myclass。将其更改为#iddiv .myclass应该可以为您解决问题。

Here's an article that goes more in depth about this : http://htmldog.com/guides/cssadvanced/specificity/

这是一篇更深入的文章:http: //htmldog.com/guides/cssadvanced/specificity/

回答by Jason Gennaro

It's not working because the first style is more specific.

它不起作用,因为第一种样式更具体。

To fix it, make sure you target the second spanmore directly, like this

要修复它,请确保您span更直接地瞄准第二个,就像这样

#iddiv span.myclass

#iddiv span.myclass

http://jsfiddle.net/jasongennaro/5fe9A/

http://jsfiddle.net/jasonennaro/5fe9A/

回答by Kon

First of all, I'd suggest you properly target your selectors, as others are suggesting.

首先,我建议您像其他人建议的那样正确定位您的选择器。

But when all else fails, you can use !important.

但是当所有其他方法都失败时,您可以使用!important

回答by woodykiddy

Remember to use the keyword, !important, which functions to overwrite parent rules.

请记住使用关键字 !important,它的作用是覆盖父规则。

Also you can define your "myclass" in the following way:

您也可以通过以下方式定义“myclass”:

#iddiv span.myclass {
    width:10px;
}