Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

What is the role of @media directive in SASS ?

  • Last Updated : 28 Nov, 2021

SASS stands for Syntactically Awesome Style Sheet. It is basically a CSS preprocessor that helps us to reduce the repetitions in the CSS code and also helps to reduce the complexity of CSS code. SASS makes the code easy to understand using different features like mixins, variables, and so on. One such important feature of SASS is the @media directive which does the work of media query in normal CSS. In this article, we will learn how to use the @media directive in SASS and it’s working.

To create a responsive website, we define different CSS styles for different screen widths and heights. This can be done using media queries in CSS, however, the code becomes very large and we have to repeat the code multiple times. SASS reduces this complexity using the @media directive. The directive allows the element to adapt to different screen widths.

Syntax:

.element {
    @media screen and (...) {

    }
}

As you can see from the above syntax, unlike CSS @media directive can be defined inside the selector which makes the code shorter and makes it easier to understand.

Example: In the below example we have changed the background color and font size according to the change in screen width using the SASS @media directives. We will link the file with the “style.css” that is generated using the sass command.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <link rel="stylesheet" 
          href="style.css">
</head>
  
<body>
    <h1>@media directive in SASS</h1>
</body>
  
</html>

SASS




body {
    background-color: rgb(95, 95, 207);
    font-size: 5rem;
    
    @media screen and (max-width : 800px) {
        background-color: rgb(150, 150, 235);
        font-size: 4rem;
    }
    
    @media screen and (max-width: 500px) {
        background-color: rgb(58, 58, 247);
        font-size: 3rem;
    }
}

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!