Raduken Raduken - 3 months ago 8
CSS Question

Sass's @content Directive Use Cases

hey guys I have a small question about @content in sass

I still not understand well how to use it, like I did read content is if you want use a mixin and insert something else there.

my question is: why I need use @content if works whithout .

my example:

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

.content-sample {
@import context--alternate-template;
background-color: black;
}


output css:

.content-sample {
margin: 0;
font-size: 14px;
background-color: black;
}


sample I a saw on web:

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



.content-sample {
@import context--alternate-template;
background-color: black;
}


output css:

.content-sample {
margin: 0;
font-size: 14px;
background-color: black;
}


so yes why I need insert @content in the mixin if works whithout.

Answer

@content is useful for inject a copy of rules inside your mixin. The correct syntax of your sample seen on the web becomes:

SCSS:

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

.content-sample {
  @include context--alternate-template {
    background-color: black;
  }
}

Note the brackets after the @include call. Now, you have the rule background-color: black; injected after font-size: 14px;.

CSS ouput:

.content-sample {
  margin: 0;
  font-size: 14px;
  background-color: black;
}

In this case, @content is useless. In fact, the most interesting usage with @content is to inject nested selectors:

SCSS:

@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;
}

CSS output:

.content-sample {
  margin: 0;
  font-size: 14px;
  background-color: black;
}
.content-sample .important-thing {
  color: red;
}
.content-sample.is-italic {
  font-family: 'my-webfont-italic';
}
Comments