Suraj
Suraj

Reputation: 36547

Change style based on containing element

Suppose I have the following html:

This a test of <code>some code</code>.
<div class='highlight'>
    <pre>
        <code class='r'>
        </code>
    </pre>

</div>

How do I structure the CSS such that the <code> blocks inside div of class highlight have a different style than <code> that is not wrapped within a div of class highlight? For example, lets say I want them to have a different background color and use different fonts.

Upvotes: 0

Views: 55

Answers (2)

Nick McCormack
Nick McCormack

Reputation: 530

div.highlight code {
  /* highlight parent only styles go here */
}

div code {
  /* default div code styles here */
}

code {
  /* default code styles here */
}

Code styles will inherit up the tree shown, so anything in "code" will show up for "div code" AND "div.highlight code", whereas code in "div code" will show up in "div.higlight code", but NOT in a plain "code" element on its own.

Upvotes: 2

mrtsherman
mrtsherman

Reputation: 39872

Use .className followed by the tag you want to style. This targets all code blocks inside anything with the highlight class.

http://jsfiddle.net/9AeS3/

.highlight code { background: gray; }

Upvotes: 0

Related Questions