Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional child selector, with CSS/Stylus/LESS: .aa > .bb? > .cc

Consider this HTML with CSS classes aa, bb and cc:

<div class='aa'>
<div class='bb'>
<div class='cc'>
</div>
</div>
</div>

I can select the class=cc tag like so: .aa > .bb > .cc. However, in my case, sometimes the .bb tag is absent, that is, the HTML looks like so:

<div class='aa'>
<div class='cc'>
</div>
</div>

Thererfore, to select all .cc close to an .aa, I'd need to specify two CSS paths:

.aa > .bb > .cc,
.aa > .cc { .... }

This works, but, is there no shorter way? Something similar to this:

.aa > (.bb >)? .cc { ... }   /* ? means "optional" */

with CSS or something like Stylus or LESS?

Motivation: In the real world, "aa" and "bb" and "cc" are somewhat longer names, and there's more stuff before and after the "aa" and "cc", and it'd be nice to not need to duplicate that stuff.

Please note: In my case, this won't work: .aa .cc because that'd match too many .ccs elsewhere on the page. The .ccs need to be either immediately below the .aa, or below .aa > .bb.

like image 885
KajMagnus Avatar asked Nov 23 '12 06:11

KajMagnus


3 Answers

For Stylus and Sass you could do this (live example for Sass):

.aa
  > .bb, &
    > .cc
      width: 10px

I couldn't find a way to do so in a one-liner for Sass, but for Less/Stylus/Scss you could do also this (live examples for Scss, for Less) :

.aa { > .bb, & { > .cc {
  width: 10px
}}}

This is not that pretty also, but still better than nothing :)

like image 120
kizu Avatar answered Oct 27 '22 11:10

kizu


Wouldn't .aa > .cc, .aa > .bb > .cc {} work? Or did I misunderstand your question?
This selects only the .cc that are direct .aa children and the .cc that are .bb children (children of .aa) as well.

like image 21
Etheryte Avatar answered Oct 27 '22 13:10

Etheryte


if you want use your option, by the way is very interesting, you can use a form most correct:

>.aa (>.bb)? >.cc { ... }

but the form correct would:

.aa .cc { ... }

into stylus:

.aa   
  .cc

thats all.

like image 1
Jorge Rojas Avatar answered Oct 27 '22 13:10

Jorge Rojas