Reputation: 9009
I have the following html:
<div class="canvas red">
<div>
<div class="canvas blue">
<div>
has blue border
<div class="canvas red">
...
<div>
MUST HAVE RED BORDER
</div>
</div>
</div>
</div>
</div>
</div>
and here is the css code:
div.canvas div {
border-style: solid;
border-width: 1px;
}
div.canvas.red div {
border-width: 4px;
border-color: red;
}
div.canvas.blue div {
border-color: blue;
}
The problems are 3:
The innermost div.canvas.red div
receives blue
border because it is inside div.canvas.blue
in the hierarchy. I need to stop this css inheritance so that the innermost div.canvas.red div
will not get twisted by div.canvas.blue
.
I cannot control the nesting of the divs above, because of dynamically inserting components in the web page. There can be various nesting scenarios that I must handle.
I must not change the css structure and the way it is applied - like canvas
and red
/blue
etc being separate class names, instead of having canvas_red
and canvas_blue
as different classes.
I do not plan to support IE6, therefore I can use the >
token in my css. However, I was unable to properly take advantage of it. I'd apreciate if you change my code using it more appropriately.
Upvotes: 1
Views: 962
Reputation: 723759
I do not plan to support IE6, therefore I can use the
>
token in my css. However, I was unable to properly take advantage of it. I'd apreciate if you change my code using it more appropriately.
This should be what you're looking for:
div.canvas > div {
border-style: solid;
border-width: 1px;
}
div.canvas.red > div {
border-width: 4px;
border-color: red;
}
div.canvas.blue > div {
border-color: blue;
}
Keep in mind that border styles are not inherited by child elements from their parents by default. The behavior you're seeing with descendant selectors is a simple effect of cascading (due to the equal specificity of your selectors), as well as the nature of the descendant selector itself to look at any level of nesting.
The child selector >
doesn't increase specificity, but it does limit the nesting depth to only one level (i.e. div.canvas.blue > div
cannot match the innermost element in <div class="canvas blue"><div><div>
), which is why the resulting styles will be different.
Upvotes: 3
Reputation: 3146
div.canvas, div.canvas div { border-style: solid; border-width: 1px; } div.canvas.red { border-width: 4px; border-color: red; } div.canvas.blue { border-color: blue; }
Upvotes: 0