Reputation: 2119
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.
Upvotes: 14
Views: 6039
Reputation: 1
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;
}
}
Upvotes: 0
Reputation: 5037
@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';
}
Upvotes: 21