krzyzws
krzyzws

Reputation: 41

Sass mixin to target odd children elements

I'm trying to create a left/right image and text layout, where for example: 1st element has the image on the left, text on the right, 2nd element has the image on the right, text on the left, 3rd element - as 1st 4th element - as 2nd

etc. The gotcha is that depending on the layout, left/right padding of the text container should also alternate between 0 and 5 em.

One simple way to do this would be to define padding for the element and then override it with a selector such as :nth-child(odd).

However, I would like to make it more elegant with a mixin/ @if rule.

Now, this is what I've got so far (applying it to the text container div):

@mixin alternating-padding() {
@if (&: nth-child(odd)) {
    padding: 5em 0 5em 5em;
} @else {
        padding: 5em 5em 5em 0;   } }

Applied:

&__text {
    @extend .col-6;
    @include alternating-padding;
    text-align: left;
  }

Which is not working. Any ideas of how I can improve this? :)

Thanks!

Upvotes: 1

Views: 977

Answers (1)

Fabian S.
Fabian S.

Reputation: 2529

A scss @if rule is evaluated when the scss gets compiled. At that point theres no DOM to check against. So there is no way you can decide if its a even or odd child by the time you compile the scss (and where the @if rule is evaluated).

Using :nth-child(odd) in css is the proper way to go.

If you still want to use a mixin, it could look like this:

@mixin alternating-padding() {
  padding: 5em 5em 5em 0;

  &:nth-child(odd) {
    padding: 5em 0 5em 5em;
  }
}

Upvotes: 1

Related Questions