a solution to control font-size relatively with media queries in Sass

Posted :

SCSS で media queries を使いながら、相対的に font-size を扱うよさ気な方法を思いついた。

I just conceived a good solution to control font-size relatively with media queries in Sass.

settings

At first, you can change…

  • base font sizes, which is referenced by reading text like

    and othres…

  • brakepoints for mediaqueries

and here is the settings and mixins

$font-size-desktop     : 12px; // base font size for desktop
$font-size-middlescreen: 14px; // base font size for tablet
$font-size-smallscreen : 16px; // base font size for smartphone

$breakpoint-desktop     : 1024px;
$breakpoint-middlescreen: 768px;
$breakpoint-smallscreen : 320px;

// do not change below this line ---

$_basefontsize: $font-size-desktop;

@function parseInt ( $x ) {
  @return $x / ( 1 + $x - $x );
}

@function fs ( $relativeSize ) {
  @return $_basefontsize + ( $relativeSize * 2 );
}

@mixin max-screen( $res ) {
  @media screen and ( max-width: $res ) {
    @if parseInt( $res ) < parseInt( $breakpoint-desktop ) {
      $_basefontsize: $font-size-desktop;
    }
    @if parseInt( $res ) < parseInt( $breakpoint-middlescreen ) {
      $_basefontsize: $font-size-middlescreen;
    }
    @if parseInt( $res ) < parseInt( $breakpoint-smallscreen ) {
      $_basefontsize: $font-size-smallscreen;
    }
    @content;
    $_basefontsize: $font-size-desktop;
  }
}

SCSS code example

And then, write some code in scss, with fs mixin and max-screen mixin. here is a example.

.myModule1 {
  font-size: fs( 0 );
  @include max-screen( $breakpoint-smallscreen ) {
    font-size: fs( 0 );
  }
}

.myModule2 {
  font-size: fs( +1 );
  @include max-screen( $breakpoint-smallscreen ) {
    font-size: fs( +1 );
  }
}

.myModule3 {
  font-size: fs( +2 );
    @include max-screen( $breakpoint-smallscreen ) {
      font-size: fs( +2 );
    }
  .myModule3__elm{
    font-size: fs( 0 );
    @include max-screen( $breakpoint-smallscreen ) {
      font-size: fs( 0 );
    }
  }
}

output

after compilation, you will get css code below

.myModule1 {
  font-size: 12px; }
  @media screen and (max-width: 320px) {
    .myModule1 {
      font-size: 14px; } }

.myModule2 {
  font-size: 14px; }
  @media screen and (max-width: 320px) {
    .myModule2 {
      font-size: 16px; } }

.myModule3 {
  font-size: 16px; }
  @media screen and (max-width: 320px) {
    .myModule3 {
      font-size: 18px; } }
  .myModule3 .myModule3__elm {
    font-size: 12px; }
    @media screen and (max-width: 320px) {
      .myModule3 .myModule3__elm {
        font-size: 14px; } }