Direct childrens and any sibling in SASS

Viewed 55

How to write in SASS all the direct childrens of my class and any sibling that has a sibling before?

.split {
  flex-direction: row;
  .split>* {
    flex-basis: 100%;
  }
  .split>*+* {
    margin-left: 2em;
  }
}
<ul class="split">
  <li>
    <p>Lorem ipsum.</p>
  </li>
  <li>
    <p>Labore reprehenderit</p>
  </li>
</ul>

2 Answers

You should use & when you want to refer to parent selector. When nesting selectors be carefull that & refers to the selector that is used to define the scpoe.

.split {
  flex-direction: row;

  /* for direct children */
  & > * {
    flex-basis: 100%;
  }

  /* .split that is placed immediately after .split */
  & + & {
    margin-left: 2em;
  }
}

The end result is in the codepen.
The trick here is to correctly understand how sass nesting works. Here is your code.

.split {
  flex-direction: row;
  .split>* {
    flex-basis: 100%;
  }
  .split>*+* {
    margin-left: 2em;
  }
}

After processing your code looks like this. You could process it online here.

.split {
    flex-direction: row;
}

.split .split > * {
    flex-basis: 100%;
}

.split .split > * + * {
    margin-left: 2em;
}

But to do what you want, you need this css.

.split {
    flex-direction: row;
}

/* > is direct children selector */
.split > * {
    flex-basis: 100%;
}

/* * + * is selector for any sibling that has a sibling before */
.split * + * {
    margin-left: 2em;
}

And corresponding scss for this css looks like this.

.split {
  flex-direction: row;
  
  > * {
    flex-basis: 100%;
  }
  
  * + * {
    margin-left: 2em;
  }
}

Check out sass documentation to understand how nesting works.

Related