Open In App

What is the @content directive used for ?

Improve
Improve
Like Article
Like
Save
Share
Report

What is @content directive? 

@content is a SASS At-rule used to reuse a block of code by reducing the repetition of the same code. It is used as a body in the @mixin to include a block of code that is passed via @include.

 

Example 1: Run the below code with the SASS preprocessor. It replaces the @content inside @mixin with the color “white” passed using @include.

CSS




@mixin example {
    @content;
}
body{
    @include example{ color : white }
}


Output :

body {
    color: white;
}

Uses of @content:

It is generally used for code replacement. You can use it with other At-rules or even in nested selectors. You will go through some use cases of @content.

Example 1: In this example, @content is used to replace the block of code for media queries. So this will help us to pass different attributes for different screen sizes. We are arranging the small screen device attributes. The media query will be applied to the screen with 600px as min-width. Likewise, we can pass a different block of code for other screen sizes.

CSS




@mixin sm($val) {
    @media screen and (min-width: $val) {
        @content;
    }
}
  
@include sm(600px) {
    body {
        color: white;
    }
}


Output :

@media screen and (min-width: 600px) {
    body {
        color: white;
    }
}

Example 2:  In this example, @content is used to assign the body to the @keyframes where,

  • $name replaces with resize 
  • @content replaces with from{. . .} to {. . .} 

This helps us to define different animations with one @mixin syntax code.

CSS




@mixin keyframes($name) {
     @keyframes #{$name} {
      @content;
    }
}
  
@include keyframes(resize) {
    from {
      width : 0%;
    }
    to {
      width : 100%;
    }
}


Output :

@keyframes resize {
     from {
           width: 0%;
     }
     to {
           width: 100%;
     }
}

Example 3: In this example, @content is used to create buttons of different text colors. This helps us to define different buttons for different purposes.

CSS




@mixin button{
    @content;
}
.alert {
   @include button 
   {
       color: red;
   }
}
.confirm {
   @include button 
   {
       color: blue;
   }   
}


Output:

.alert {
   color : red;
}
.confirm {
   color : blue;
}

Example 4: In this example, @content is used in nested selectors where .child-attr is passed inside the  .parent class.

CSS




@mixin child {
     @content
}
.parent {
   @include child {
       .child-attr {
         color: red;
       }
   }
     background-color: green;
}


Output :

.parent {
     background-color: green;
}
.parent .child-attr {
     color: red;
}


Last Updated : 09 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads