What is @apply in CSS?

Issue

I’m curious what the CSS directive @apply does. I have googled @apply but I couldn’t find anything that could explain its meaning properly for me.

What is the usage of such a directive?

Solution

the simple way of explaining it would be; introducing variables into css (which is a feature of preprocessors such as sass), and mixins which are function like behaviors (also in preprocessors).

imagine that --header-theme is a function (mixin)

:root {
  --header-theme: {
    color: red;
    font-family: cursive;
    font-weight: 600;
  };
}
  
h1 {
  @apply --header-theme;
}


h2 {
  @apply --header-theme;
}

this way you can use it in many different places without having to rewrite it again DRY

now the variable part could explain with this example

:root {
  --brand-color: red;/*   default value*/
  --header-theme: {
    color: var(--brand-color);
    font-family: cursive;
    font-weight: 600;
  };
}
  
h1 {
  @apply --header-theme;
}


h2 {
  --brand-color: green; 
  @apply --header-theme;
}

the mixin will have a variable sent to it and change the color

this is not the limits of the feature, you can use it for far more, you can read more about mixin and variables in SASS for other ways of using it, after I suggest you read this blog post

now after I got you excited, time for the bad news, it is not implemented in browsers yet chrome, it is still worth knowing that it is coming and maybe if you want to prepare yourself start with SASS

Answered By – oqx

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.