Open In App

How to load window width value to SCSS variable ?

Last Updated : 02 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The task is to load the window width value to an SCSS variable and use it. Let us take a brief introduction to an SCSS.

SCSS Variables can store any kind of value color, font-family, font-size, clip-path values, etc, and are mainly used to maintain the reusability of code across the stylesheets.

Approach:

  • Step 1: Define a function in SCSS and generate the precise viewport width values to acquire the window width 

    @function get-vw($target) { 
      $vw-context: (1000*.01) * 1px;
      @return ($target/$vw-context) * 1vw;
    }
  • Step 2: Pass in a value in pixels to this function and store it in an SCSS variable.

    $window-width: get-vw(72px);

    Since viewport-width is 1% of the viewport we can scale the size in px as a ratio.

  • Step 3: Use the variable wherever needed.

    main.scss




    $window-width: get-vw(72px); /* Passing in a value in pixels */
      
    /* Defining the function to generate the window width* /
    @function get-vw($target) { 
      $vw-context: (1000*.01) * 1px;
      @return ($target/$vw-context) * 1vw;
    }
      
    /* Setting the default values*/
    *{
      padding : 0;
      margin : 0;
      box-sizing: border-box;
    }
      
    /* Using the property*/
    .misc{
      padding: 3rem 0;
      color: #fff;
      width: $window-width;
      text-align: center;
      font-size: 1.8rem;
      background-color:green;
    }

    
    

    Output: This would result in the following CSS.

    main.css




    /* Passing in a value in pixels */
    /* Defining the function to generate the window width*/
    /* Setting the default values*/
    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }
      
    /* Using the property */
    .misc {
      padding: 3rem 0;
      color: #fff;
      width: get-vw(72px);
      text-align: center;
      font-size: 1.8rem;
      background-color: green;
    }

    
    

    Note: Here, mentioning box-sizing: border-box is really important here because this would render the DOM to remove any default margin or spaces.

    index.html




    <!DOCTYPE html>
        <html>
         <body>
            <div class="misc">
               GeeksforGeeks
            </div>
         </body>
    </html>

    
    

    Output: Here, our text is taking up the whole width of its current screen.

    Note: Though there are javascript methods like window.outerWidth, we cannot possibly store those values in an SCSS variable since SCSS is just a pre-processor.



    Like Article
    Suggest improvement
    Share your thoughts in the comments

Similar Reads