Fabio Costa
Fabio Costa

Reputation: 51

What's is @content used for in Sass?

I'm learning SCSS, and I stumbled upon @content. I really don't understand what its use is, since up until now I'm able to get the same output without it. Example:

@mixin context--alternate-template {
  margin: 0;
  font-size: 14px;
  @content
}

.content-sample {
  @include context--alternate-template {
    .important-thing {
      color: red;
    }
    &.is-italic {
      font-family: 'my-webfont-italic';
    }
  }

  // outside mixin call
  background-color: black;
}

gets the same output as

@mixin context--alternate-template {
  margin: 0;
  font-size: 14px;
}

.content-sample {
    
    @include context--alternate-template;
  
    .important-thing {
      color: red;
    }
    &.is-italic {
      font-family: 'my-webfont-italic';
    }

  // outside mixin call
  background-color: black;
}

Can someone give me a good example where @content is actually useful (so there is no other way to get the same output without @content, or without making the code a lot more complex without it)?

Upvotes: 5

Views: 3227

Answers (2)

Simplicius
Simplicius

Reputation: 2095

It's mainly useful in conjunction with @media queries or other "generated* rules.

E.g.

$breakpoints: (
  "mobile-s": 320px,
  "mobile-m": 475px,
);

@mixin forBreakpoint($breakpoint) {
  @for $i from 1 through length($breakpoints) {
    @if nth(nth($breakpoints, $i), 1) == $breakpoint {
      @media (min-width: #{nth(nth($breakpoints, $i), 2)}) {
        @content;
      }
    }
  }
}

.foo {
  @include forBreakpoint(mobile-s) {
    foo: foo;
  }
}

.bar {
  @include forBreakpoint(mobile-m) {
    bar: bar;
  }
}

Will output:

@media (min-width: 320px) {
  .foo {
    foo: foo;
  }
}

@media (min-width: 475px) {
  .bar {
    bar: bar;
  }
}

Upvotes: 0

Romko
Romko

Reputation: 1798

@content keyword is meant to include content, passed from the place of invocation, therefore you can customise your @mixin by including context-sensitive scss code.

@mixin apply-to-ie6-only {
  * html {
    @content
  }
}

@include apply-to-ie6-only {
  #logo {
    background-image: url(/logo.gif);
  }
}

Take a look at this example: https://thoughtbot.com/blog/sasss-content-directive

Upvotes: 4

Related Questions