简体   繁体   中英

Two styles with different colors

Is that possible to have two styles for one element with different colors?

In other words, lets suppose I have following HTML code:

<table class='my_table'>
<th class="style1 style2">LastName</th>
...
</table>

and following CSS:

.my_table th.style1 { 
    background: #aaaaaa; 
}

.my_table th.style2 { 
    background: #bbbbbb; 
} 

I understand that I can remove one style with JavaScript for some condition. But I would like to have two styles and one of them should override another. Is that possible?

The last defined styles (not classes in your class attribute) should be applied on your element, to answer your question. But if somewhere was made use of the !important keyword, the results can come very strange to you.

Yes, you can use any number of classes on an element. CSS uses both the declaration order and the specificity of the selectors to decide which will be overriden.

For example, if the specificity is the same, the last one is used:

.style1 { 
    background: #aaaaaa; 
}

.style2 { 
    background: #bbbbbb; 
} 

Otherwise, the most specific will be used (the first one on the example below):

.my_table th.style1 { 
    background: #aaaaaa; 
}

.style2 { 
    background: #bbbbbb; 
}

Yes, you can use more than one class for an element, and all style rules for those classes are applied.

If rules conflict, the rule that is most specific overrides the other. If rules are equally specific, the last rule applies.

Example:

<table class="my_table">
    <tr>
        <th class="style1">Style 1</th>
        <th class="style2">Style 2</th>
        <th class="style1 style2">Style 1 and 2</th>
    </tr>
</table>

The third cell will get the background from style2 , as it is defined last in the style sheet.

Demo: http://jsfiddle.net/jsLP5/

是的,您可以将多个类应用于元素,如果相同的CSS元素存在竞争定义,则会覆盖另一个。

You can have as many style definitions as you want in general or for a specific element. Which one is used is based off the css specificity (scope). You can read more here: http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

yes u can

       <th class="style1 style2">LastName</th>

and the css is yours as it discribed here

http://webdesign.about.com/od/css/qt/tipcssmulticlas.htm

For the given code, the background color used is #bbbbbb, since other things being equal, as they are here, the latter declaration wins, by the cascade rules . This means the order of the CSS declarations. The order of class names in the class attribute is immaterial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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