Search code examples
csssasscalc

Stepwise calculation based on window width in CSS


I need to make a calculation that every 100px of window width + 2% css increased in the left %:

Examples:

  • width > 700px: left: 30%
  • width > 800px: left: 32%

How I can do this?


Solution

  • It's not currently possible to write a single CSS ruleset that increments a property stepwise every 100 pixels of window width in all major browsers. You'll need to write a separate media query for each interval.

    In SCSS, you can do this with a loop. This will create a media query for $number-of-intervals number of steps starting at $base-width width and $base-percentage percentage:

    $base-width: 600px;
    $base-percentage: 30%;
    $number-of-intervals: 6;
    @for $i from 1 through $number-of-intervals {
      @media screen and (min-width: #{$base-width + (($i - 1) * 100)}) {
        .my-class {
          left: #{$base-percentage + (($i - 1) * 2)};
        }
      }
    }