Skip to content

Instantly share code, notes, and snippets.

@narekmal
Last active July 25, 2022 06:19
Show Gist options
  • Save narekmal/609c37e48a664a62d748e04851504083 to your computer and use it in GitHub Desktop.
Save narekmal/609c37e48a664a62d748e04851504083 to your computer and use it in GitHub Desktop.
SCSS utilities for using vw units

The Function

Suppose we want a div to have 50px width when the screen width is 500px and a proportionate width when the screen width changes. We do math: (50/500)*100 = 10 and set width: 10vw. The following simple function helps make our intention more clear:

@function get-vw($valueAtWidth, $width) {
    @return $valueAtWidth*100vw/$width;
}

Usage: width: get-vw(50px, 500px);

The Mixin

Now suppose we want the same div have fixed width for wide screens and start scaling proportionally when screen width goes smaller than 500px. We could do like this:

@media screen and (max-width: 500px) {
    #theDiv {width: get-vw(50px, 500px)}
}

Or we could:

@mixin set-vw-sm($property, $valueAtWidth, $width) {
    @media screen and (max-width: #{$width}) {
        #{$property}: $valueAtWidth*100vw/$width;
    }
}
#theDiv {@include set-vw-sm('width', 50px, 500px)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment