主页 > 互联网  > 

使用scss简化媒体查询

使用scss简化媒体查询

在进行媒体查询的编写的时候,我们可以利用scss与与编译器,通过@include混入的方式对代码进行简化,从而大大提高了代码的可维护性,也减少了代码的编写量,废话不多说,直接上代码:

// 断点列表 相当于js中的数组,只不过这里数组用()表示 $breakpoints: ( "phone": ( 320px, 480px, ), "pad": ( 481px, 768px, ), "notebook": ( 769px, 1024px, ), "pc": ( 1025px, 1200px, ), // 大屏 "tv": 1201px, ); // 混合 @mixin respond-to($breakname) { // map-get函数可以拿到上面定义的map数组中的值 $bp: map-get($breakpoints, $breakname); // type-of用于判断上面的键是否是数组/列表类型 @if type-of($bp) == "list" { $min: nth($bp, 1); // 拿到设备尺寸的最小值, 列表中的第一个值 $max: nth($bp, 2); // 拿到设备尺寸的最大值, 列表中的第二个值 // >= 最小值 and <= 最大值 @media (min-width: $min) and (max-width: $max) { // 类似于vue中的插槽,在此处挖一个坑,外面可以往里面传入不同的css样式 // 比如:下面代码示例中传入的是heigth的值 @content; } } @else { @media (min-width: $bp) { @content; } } } // 编写scss代码 .header { display: flex; width: 100%; background-color: pink; @include respond-to("phone") { height: 50px; } @include respond-to("pad") { height: 60px; } @include respond-to("notebook") { height: 80px; } @include respond-to("pc") { height: 100px; } @include respond-to("tv") { height: 200px; } }

最终编译的结果:

.header { display: flex; width: 100%; background-color: pink; } @media (min-width: 320px) and (max-width: 480px) { .header { height: 50px; } } @media (min-width: 481px) and (max-width: 768px) { .header { height: 60px; } } @media (min-width: 769px) and (max-width: 1024px) { .header { height: 80px; } } @media (min-width: 1025px) and (max-width: 1200px) { .header { height: 100px; } } @media (min-width: 1201px) { .header { height: 200px; } }

如此一来,编写响应式布局就变得十分方便了~

标签:

使用scss简化媒体查询由讯客互联互联网栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“使用scss简化媒体查询