Sass's @content Directive Use Cases
Asked Answered
L

2

14

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.

Leilani answered 13/5, 2016 at 8:52 Comment(0)
H
21

@content is useful for injecting 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 output:

.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';
}
Horacehoracio answered 14/5, 2016 at 7:45 Comment(1)
this example should be added to the sass documentation. Thanks!Inman
P
0

One more use case of @content that helped me to see its value - media queries

SCSS:

@mixin desktop {
    @media screen and (min-width: $desktop-size) {
        @content;
    }
}

.main {
    display: flex;
    flex-direction: row;
    
    
    @include desktop{
        flex-direction: column;
    }
}

CSS output

.main {
  display: flex;
  flex-direction: row;
}
@media screen and (min-width: 60rem) {
  .main {
    flex-direction: column;
  }
}
Playback answered 1/12, 2022 at 20:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.