CSS 多类属性覆盖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8127337/
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 02:10:01  来源:igfitidea点击:

CSS multiple classes property override

css

提问by iandisme

If I have a style class defined as such:

如果我有一个这样定义的样式类:

.myclass{
    //bunch of other stuff
    float:left;
}

and I define another class like this:

我定义了另一个这样的类:

.myclass-right{
    float:right;
}

and I define a div this way:

我以这种方式定义了一个 div:

<div class="myclass myclass-right"></div>

Will that div inherit everything from myclass, but override the float property to float:right? That's what I'd expect to happen. Also kind of want to know if that has any cross-browser implications (good browsers vs. IE 7 or greater, f*** IE6).

该 div 会继承 myclass 的所有内容,但将 float 属性覆盖为 float: 对吗?这就是我希望发生的事情。还想知道这是否有任何跨浏览器的影响(良好的浏览器与 IE 7 或更高版本,f*** IE6)。

回答by steveax

As long as the selectors have the same specificity (in this case they do) and .myclass-rightstyle block is defined after .myclass, yes.

只要选择器具有相同的特性(在这种情况下它们是相同的)并且.myclass-right样式块在 之后定义.myclass,是的。

Edit to expand: the order the classes appear in the html element has no effect, the only thing that matters is the specificity of the selector and the order in which the selectors appear in the style sheet.

编辑展开:类在 html 元素中出现的顺序没有影响,唯一重要的是选择器的特殊性和选择器在样式表中出现的顺序。

回答by John Hartsock

Using !importantis one way to do it.

使用!important是一种方法。

.myclass-right{
    float:right !important;
}

In addition if you are more specific with your selector it should override as well

此外,如果您对选择器更具体,它也应该覆盖

div.myclass-right{
    float:right;
}

回答by streetlogics

Just wanted to throw out another option in addition to !important as well as style definition order: you can chain the two together as well:

除了 !important 和样式定义顺序之外,只想抛出另一个选项:您也可以将两者链接在一起:

.myclass.myclass-right{float:right;}
.myclass{float:left;}

回答by Leo

As long as myclass-rightis declared afteryour other class in your css file, it will work.

只要在 css 文件中的其他类之后myclass-right声明,它就会起作用。

回答by Sergei Panfilov

In case of a conflict, the css tag that comes afterhas a priority.

如果发生冲突,后面的 css 标签具有优先权。

In other words - if you want some class to ever override others - just put it on end of your css file.

换句话说 - 如果您希望某个类覆盖其他类 - 只需将其放在 css 文件的末尾。

P.S. But don't forget that more specific rules has more priority, like .a.b {}is more powerful than just .a{}

PS但是不要忘记更具体的规则有更多的优先级,like.a.b {}比只是更强大.a{}