moritzgvt
moritzgvt

Reputation: 444

Using the CSS sibling selector (+) along with the SCSS parent selector (&) within a nested structure

I am often trying to style the next sibling of an element with SCSS, within a nested structure as the following:

  <div class="grand_parent">
    <div class="parent">
      <div class="parent__child-1"></div>
      <div class="parent__child-2"></div>
    </div>
  </div>
/* SCSS Code */

.grand_parent {
  .parent {
    &__child-1 + &__child-2 {
     /* do some stuff */
    }
  }
}

The output of the above SCSS (using node-sass for compilation) is similar to the following. Which isn't working unfortunately.

/* CSS Output */

.grand__parent .parent .parent__child-1 + .grand__parent .parent .parent__child-2 {  
  /* do some stuff */
}

What I am expecting is the following output, which isn't possible since the parent selector returns the complete parent with the nested structure.

/* Expected CSS Output */

.grand__parent .parent .parent__child-1 + .parent__child-2 {
  /* do some stuff */
}

This output can be generated when not using the second parent selector in along with the sibling selector, like so &__child-1 + .parent__child-2. Which is the method I am using. But I think it would be more readable and convenient if I could also use the parent selector here.

Don't get me wrong: I think this is definitely the correct behaviour, since it maintains the scoping of the parent. But I would like to know if there's a workaround for that or of I did something wrong … I've often stumbled over this problem and always solved it without really thinking about it.

Upvotes: 0

Views: 2212

Answers (1)

sramirez0
sramirez0

Reputation: 10

This code will give you the expected CSS:

.grand__parent {
  .parent {
    .parent__child-1 {
      & + .parent__child-1 {
        //styles here
      }
    }
  }
}

Upvotes: 0

Related Questions