JasperJ
JasperJ

Reputation: 1222

CSS: Selecting a group of parents

For the following generated HTML:

<div id="parent1">
   <div class="child" />
</div>
<div id="parent2"> 
    <div class="child" />
</div>
<div id="parent3"> 
    <div class="child" />
</div>

I would like to select .child from #parent1 and #parent2 like:

#parent1 .child, #parent2 .child { Do stuff... }

However, this can become messy. Is it possible to select a group of parents like this?

(#parent1, #parent2) .child { Do stuff... }

Upvotes: 3

Views: 978

Answers (3)

Oriol
Oriol

Reputation: 288130

Selectors L4 draft introduces :matches(). It allows you to do

:matches(#parent1, #parent2) .child

Note it's an experimental feature, and browsers haven't implemented it yet. However, some support :-moz-any or :-webkit-any, which behave like :matches.

:-moz-any(#parent1, #parent2) .child {
  color: blue;
}
:-webkit-any(#parent1, #parent2) .child {
  color: blue;
}
:matches(#parent1, #parent2) .child {
  color: blue;
}
<div id="parent1">
  <div class="child">Child</div>
</div>
<div id="parent2"> 
  <div class="child">Child</div>
</div>
<div id="parent3"> 
  <div class="child">Child</div>
</div>

Upvotes: 3

Richard JP Le Guen
Richard JP Le Guen

Reputation: 28753

What you're looking for is nesting, and you'll need to use SASS or SCSS for that: http://jsfiddle.net/soy3tdmy/

#parent1, #parent2 {
    .child {
        color: red;
        text-decoration: underline;
    }
}

Upvotes: 0

lmgonzalves
lmgonzalves

Reputation: 6588

In this case you can use the [attribute^=value] (begin with) or [attribute*=value] (contain) syntax.

HTML:

<div id="parent1">
    <div class="child">child</div>
</div>
<div id="parent2"> 
    <div class="child">child</div>
</div>
<div id="anotherParent"> 
    <div class="child">child</div>
</div>

CSS:

[id^=parent] .child {
    color: red;
}

DEMO: https://jsfiddle.net/lmgonzalves/eh5saf1k/

But I think it's better to asign the same class simply.

Upvotes: 1

Related Questions