使用 sass 实现响应式 web 页面

响应式的 web 设计要求网页在不同尺寸的屏幕上有不同的表现

这可以分解为两个动作

  • 识别屏幕的尺寸
  • 在某一尺寸下显示相应的内容

我们看一下如何用 sass 做这些事情


为断点命名

1
2
3
4
5
$breakpoints: (
'medium': (min-width: 800px),
'large': (min-width: 1000px),
'huge': (min-width: 1200px),
);

我们利用宽度将显示设备分为三类:大于 800px 的大于 1000px 的大于 1200px 的

断点管理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@mixin respond-to($breakpoint) {
$raw-query: map-get($breakpoints, $breakpoint);

@if $raw-query {
$query: if(
type-of($raw-query) == 'string',
unquote($raw-query),
inspect($raw-query)
);

@media #{$query} {
@content;
}
} @else {
@error 'No value found for `#{$breakpoint}`. '
+ 'Please make sure it is defined in `$breakpoints` map.';
}
}

我们写一个叫作 respond-tomixin 作为断点的管理器

管理器会从 $breakpoints 里取得参数所对应的宽度,应用到 respond-to 下的 @content

使用媒体查询

1
2
3
4
5
6
7
.foo {
color: red;

@include respond-to('medium') {
color: blue;
}
}

.foo 下使用我们定义好的 respond-to 这个 mixin,要求在 medium 这个尺寸下将 color 设置为 blue

这里的 color: blue 就是上面提到的 @content

上述写法最终会被编译为:

1
2
3
4
5
6
7
8
9
.foo {
color: red;
}

@media (min-width: 800px) {
.foo {
color: blue;
}
}

原文作者: dgb8901,yinxing

原文链接: https://www.itwork.club/2018/08/01/reponsive-web-weith-sass/

版权声明: 转载请注明出处

为您推荐

体验小程序「简易记账」

关注公众号「特想学英语」

web 页面性能统计