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.
The @content, aka content directive, is “simple” in that it provides a way to reduce repetitive code, allowing for reuse and easier changes throughout the codebase.
The @content directive is a way to pass a block of styles to a mixin, this is useful in cases when you don't want to limit your future self in terms of number of parameters a mixin can accept.
When you write Sass code in a . scss file, it is compiled into a regular CSS file that the browser will use to display it on the web page.
The SASS @import function helps us to import multiple SASS or CSS stylesheets together such that they can be used together. Importing a SASS file using the @import rule allows access to mixins, variables, and functions to the other file in which the other file is imported.
@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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With