stackh34p
stackh34p

Reputation: 9009

I need to limit CSS style cascading

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:


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

Answers (2)

BoltClock
BoltClock

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

okyanet
okyanet

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

Related Questions