Jack
Jack

Reputation: 245

How to make a CSS rule act differently inside another div tag?

Let’s say I have a CSS rule:

.rule1 {
    background: #FFF;
}

I want this CSS rule to act differently inside another div tag, like this:

<div class="container">
<div class="rule1"></div> <!-- End of Rule1 -->
</div> <!-- End of Container -->

If this rule1 div is located inside the container div, I want .rule1’s background to be #CCC.

How do I specify this in CSS?

I have seen and tried something like this:

.container: rule1 {background:#CCC}

But it didn't work.

Thanks.

Upvotes: 0

Views: 745

Answers (5)

surya singh
surya singh

Reputation: 277

.container .rule{
     /*your valid css rule*/
}

Upvotes: 0

Travis J
Travis J

Reputation: 82267

jsFiddle Demo

You would need to use specificity to target that rule when nested, and then set its definitions to inherit or to whichever alternative you were interested in.

So for this structure

<div class="container">
 <div class="rule1">rule1 nested</div>
</div>
<div class="rule1">rule1</div>

That would look like this

.rule1 {
 background:#000;
 color:#fff;
}
.container .rule1{
 background:inherit;/*or alternative definition*/
 color:inherit;/*or alternative definition*/
}

Upvotes: 0

OneOfOne
OneOfOne

Reputation: 99225

.rule1 {
     background:#FFF;
}
div.rule1 { /* if you want it applied just for divs with that class */
    background:#CCC;
}
.container .rule1 { /* if you want it applied to any child of .container */
    background:#111;
}

.container div.rule1 { /* if you want it applied to any child of .container that is only a div */
    background:#111;
}

Upvotes: 0

Anonymous
Anonymous

Reputation: 12017

You don't need the colon:

.container .rule1 {
    background: #CCC;
}

Upvotes: 1

helion3
helion3

Reputation: 37361

.container .rule1 {  }

CSS nesting selector, meaning .rule1 is inside .container

Upvotes: 3

Related Questions