I do not know if is possible in CSS, but I would like a general Role to don't apply to a specific element in my case id=special
.
In my example all the DIV should be red but I want only id=special
to have not applied this color.
I understand I can always overwrite the element with id=special
but I'm interested to know if is possible have some sort of exclusion from the general Role.
Any idea in CSS 2 and CSS 3?
Example:
<div>this is red</div>
<div>this is red</div>
<div id="special">this one must be blus</div>
div>this is red</div>
// My General Role
div
{
background-color:Red;
}
In CSS, to exclude a particular class, we can use the pseudo-class :not selector also known as negation pseudo-class or not selector. This selector is used to set the style to every element that is not the specified by given selector. Since it is used to prevent a specific items from list of selected items.
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)
An inline CSS is used to apply a unique style to a single HTML element. An inline CSS uses the style attribute of an HTML element.
CSS2 Solution
div {
color: red;
}
div#special {
color: inherit;
}
demo: http://jsfiddle.net/zRxWW/1/
CSS3 allows for the :not()
selector:
div:not([id])
-or-
div:not(#special)
depending on what you want to exclude
You can read all about the selectors in the w3c docs.
As for CSS2, there's a limited set of selectors, and they don't account for negation.
CSS3 solution:
div:not(#special)
You would want to use div:not(#special)
, but if it's going to be blue anyways then you might as well just override the rule. The :not()
selector is a CSS3 property and thus isn't supported by all browsers.
This is a great example of how CSS specificity works. A general rule applying to all elements of a certain type (your div
rule turning the background red) is superseded by the more specific rule applying to an ID. This concept has existed since CSS1, and is available in all browsers. Thus:
div {
background-color:red;
}
#special {
background-color: blue;
}
... will leave all divs red. By applying the special
id to a div, that one div will be blue instead.
See it in action: http://jsfiddle.net/9Hyas/
Check out these articles for more about CSS specificity: http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/ and http://www.htmldog.com/guides/cssadvanced/specificity/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With