Possible Duplicate:
How do I prevent CSS inheritance?
Is there a way to declare the CSS property of an element such that it will not affect any of its children or is there a way to declare CSS of an element to implement just the style specified and not inherit any of the style declared for its parents?
A quick example
HTML:
<body>
<div id="container">
<form>
<div class="sub">Content of the paragraph
<div class='content'>Content of the span</div>
</div>
</form>
</div>
</body>
CSS:
form div {font-size: 12px; font-weight: bold;}
div.content
{
/* Can anything go here? */
}
Under normal circumstances one would expect the text block "Content of the paragraph" and "Content of the span" will both be 12px and bold.
Is there a property to include in the CSS above in the "div.content" block that will prevent it from inheriting the declaration in the "#container form div" block to limit the style to just "content of the paragraph" and spare "Content of the span" including any other children div?
If you are wondering why, well, I created a particular CSS file that gives all the forms on my project a particular feel and the div
elements under the form all inherit the feel. No problem. But inside the form I want to use Flexigrid but flexigrid inherits the style and it just looks useless. If I use flexigrid outside the form and such it won't inherit the forms css, then it looks great. Otherwise it just looks terrible.
Unfortunately, you're out of luck here.
There is inherit
to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).
You will have to revert style changes manually:
div { color: green; }
form div { color: red; }
form div div.content { color: green; }
If you have access to the markup, you can add several classes to style precisely what you need:
form div.sub { color: red; }
form div div.content { /* remains green */ }
Edit: The CSS Working Group is up to something:
div.content {
all: revert;
}
No idea, when or if ever this will be implemented by browsers.
Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)
Edit 3: default
was renamed to revert
.
Can't you style the forms themselves? Then, style the divs accordingly.
form
{
/* styles */
}
You can always overrule inherited styles by making it important:
form
{
/* styles */ !important
}
CSS rules are inherited by default - hence the "cascading" name. To get what you want you need to use !important:
form div
{
font-size: 12px;
font-weight: bold;
}
div.content
{
// any rule you want here, followed by !important
}
精彩评论