2

Is there a way I can add pseudo class to parent element from nested child. USING CSS ONLY

Example: In .less file, this is what I have.

.collection {
  // Some styling
    .headingRow {
        //Some styling
        .heading{
           //Some styling
           // This is where i want it to add the styling for alternate .collection class

         }
     }
 }

This is what I want as Output

.collection:nth-of-type(2n+1) .headingRow .heading 
{
    background-color:  #7a003d; 
}
.collection:nth-of-type(2n) .headingRow .heading
{
    background-color:  #322f31;
}

This is what I tried - Adding & from .heading class, I can add a parent elemnt or class using something like

    .collection {
  // Some styling
    .headingRow {
        //Some styling
        .heading{
           div&
           // This results in div.collection .headingRow .heading { }
         }
     }
 }

Is there a way I can add Pseudo class to parent ancestor ?

Ani
  • 4,241
  • 4
  • 23
  • 29

1 Answers1

7

Something like this:

.collection {
    // ...
    .headingRow {
        // ...
    }
}

.headingRow .heading {
    .collection 
        & {background-color: red}
    .collection:nth-of-type(2n) 
        & {background-color: blue}
    .collection:nth-of-type(2n + 1)
        & {background-color: green}
}

Though I don't think it's any way better than just plain old CSS like definition w/o any nesting.

seven-phases-max
  • 11,491
  • 1
  • 41
  • 57
  • Sorry i had a typo in my question. See Desired output. – Ani Apr 27 '14 at 00:27
  • @seven-phases-max I have more classes at the level of heading Row...which will require the default styling of `.collection`..I'll have to write the default styling of `collection` again in all selectors ? – Ani May 18 '14 at 20:20
  • 3
    Well, what you have to write depends on what you need to get. Obviously if you need *different* styles for *different* `collection` descendants you'll have to get these styles written somehow. Use [`mixins`](http://lesscss.org/features/#mixins-parametric-feature) and/or [`extend`](http://lesscss.org/features/#extend-feature) to minimize a repetitive code (if any). See for example http://stackoverflow.com/questions/23551080 (it's actually pretty similar thing expect that instead of `color` suffix for generated classes you'll need `nth-of-type(2n + @i)` one). – seven-phases-max May 18 '14 at 20:40