Using Sass Variables with CSS3 Media Queries

后端 未结 7 2130
醉话见心
醉话见心 2020-11-22 14:06

I\'m trying to combine the use of a Sass variable with @media queries as follows:

$base_width:1160px;

@media screen and (max-width: 1170px) {$base_width: 96         


        
相关标签:
7条回答
  • 2020-11-22 14:53

    Two recommendations

    1 Write your "default" CSS statements to be for small screens and only use media queries for larger screens. There's usually no need for a max-width media query.

    Example (assuming the element has class "container")

    @mixin min-width($width) {
      @media screen and (max-width: $width) {
        @content;
      }
    }
    
    .container {
      width: 960px;
    
      @include min-width(1170px) {
        width: 1160px;
      }
    }
    

    2 Use CSS variables to solve the problem, if you can.

    @mixin min-width($width) {
      @media screen and (max-width: $width) {
        @content;
      }
    }
    
    :root {
      --container-width: 960px;
      @include min-width(1170px) {
        --container-width: 1160px;
      }
    }
    
    .container {
      width: var(--container-width);
    }
    

    Note:

    Since it will have the width of 1160px when the window has a width of 1170px, it may be better to use a width of 100% and max-width of 1160px, and the parent element might have a horizontal padding of 5px, as long as the box-sizing property is set to border-box. There are a lot of ways to solve the problem. If the parent is not a flex or grid container you might use .container { margin: auto }.

    0 讨论(0)
提交回复
热议问题