tags:

views:

89

answers:

6

I have the following CSS:

.foo .bar {
   background: red;
}

Which works fine for the following HTML:

<div class="foo">
    <div class="bar">I have a red background</div>
</div>

But I can't seem to find a way to reuse the CSS definition when I'm not in a parent/child relationship. For example, how could I apply the same CSS to the following DIV:

<div class="???">I want a red background!</div>
+7  A: 

You can use a comma to indicate multiple selectors that a CSS rule should apply to

.foo .bar, .??? {
   background: red;
}
bdukes
+1, Just beat me.
Johrn
+9  A: 

You can add additional selector with comma (,) as specified in W3C selectors grouping

.foo .bar, .foobar {
   background: red;
}

this would work in both

<div class="foo">
    <div class="bar">I have a red background</div>
</div>

and

<div class="foobar">I want a red background!</div>
Gaby
Faster, Stronger, Bigger (Daft Punk)
enguerran
@enguerran, *chuckle*
Gaby
+1  A: 

Use a comma separated list of selectors in the definition:

.foo .bar, .otherSelector, #someID{
    background: red;
}
Johrn
A: 
.foo .bar, .redback {
     background: red;
}

will do a magic with

<div class="redback">I want a red background!</div>

or get rid of hierarchy and use only

.bar {
     background: red;
}

which will work both cases

Vestel
A: 

Try

.foo .bar, .foobar {
   background: red;
}

with

<div class="foo">
    <div class="bar">I have a red background</div>
</div>

<div class="foobar">I want a red background!</div>
enguerran
A: 

The ".foo .bar" CSS definition is written expressly for a parent-child (more accurately ancestor-decendent) relationship.

You could write the CSS like this:

.alternate-background {
   background: red;
}

and the HTML like this:

<div>
    <div class="alternate-background">I have a red background</div>
</div>

which would allow you also to use this:

<div class="alternate-background">I want a red background!</div>
Drew Wills