Using rem units in media queries and as width

前端 未结 3 1505
执念已碎
执念已碎 2020-12-31 10:12

When using rem units in Google Chrome (or firefox), the result is unexpected. I\'v set up a page with the root font-size set to 10px to make it easier the translate a pixel

3条回答
  •  忘掉有多难
    2020-12-31 11:16

    The size of 1rem in media queries is not affected by changes to the base font size. But you could calculate the correct breakpoint yourselves. You can calculate the breakpoint in pixels based on your new base font size and the desired size in rems.

    pixels = desired-rem-value * current-base-font-size
    

    For example for a base font size of 18px and a breakpoint at 20 "rem":

    20 * 18px = 360px
    

    There are a few options how to calculate the pixel value:

    1. calculate by hand:

    html {
      font-size: 18px;
    }
    
    /* For a breakpoint at 20 times your base font size*/
    @media(min-width: 360px) {
      ...
    }
    

    2. Use calc():

    @media(min-width: calc(20 * 18px)) {
      ...
    }
    

    3. Use a CSS prepocessor function: (For example in scss or something similar.)

    $base-font-size: 18px;
    
    html {
      font-size: $base-font-size;
    }
    
    @function media-rem($rem) {
      @return $rem * $base-font-size; // $rem must be unitless
    }
    
    @media(min-width: media-rem(20)) {
      ...
    }
    

提交回复
热议问题