针对响应式宽度的设计
本文档概述了用于让 Discourse 用户界面适应不同宽度的 API,既包括浏览器视口,也包括页面上的单个容器。
我们采用“移动优先”的设计,然后根据需要为更大的尺寸添加自定义。我们使用的断点如下:
| 断点 | 大小 | 像素(正文 16px 字号时) |
|---|---|---|
| xs | 20rem | 320px |
| sm | 40rem | 640px |
| md | 48rem | 768px |
| lg | 64rem | 1024px |
| xl | 80rem | 1280px |
| 2xl | 96rem | 1536px |
视口大小
使用这些断点最常见的方式是基于浏览器的视口大小。要在 SCSS 文件中使用它们,需在文件顶部添加 @use "lib/viewport";,然后使用可用的 mixin 之一:
@use "lib/viewport";
@include viewport.from(lg) {
// SCSS rules here will be applied to
// devices larger than the lg breakpoint
}
@include viewport.until(sm) {
// SCSS rules here will be applied to
// devices smaller than the sm breakpoint
}
@include viewport.between(sm, md) {
// SCSS rules here will be applied to
// devices with a size between the sm
// and md breakpoints
}
通常来说,SCSS 是处理基于视口大小的布局差异的推荐方式。对于高级场景,可以在 Ember 组件中通过 capabilities 服务访问相同的断点。例如:
import Component from "@glimmer/component";
import { service } from "@ember/service";
class MyComponent extends Component {
@service capabilities;
<template>
{{#if this.capabilities.viewport.lg}}
This text will be displayed for devices larger than the lg breakpoint
{{/if}}
{{#unless this.capabilities.viewport.sm}}
This text will be displayed for devices smaller than the sm breakpoint
{{/unless}}
</template>
}
这些属性是响应式的,当浏览器窗口大小改变时,Ember 会自动重新渲染模板的相关部分。
实际示例请查看 app/assets/stylesheets/common/base/directory.scss,它通篇使用 viewport.until(sm)/viewport.until(md),以便在较窄的视口宽度下调整用户目录表格的布局。
容器查询
有时,组件的布局需要响应其自身容器的大小,而非整个浏览器视口的大小。例如,一张卡片既可能以全宽渲染,也可能渲染在较窄的边栏内。对于这些情况,请使用 lib/container,它与 lib/viewport 共享相同的断点体系和 mixin API。
容器查询只对通过 container-type 显式声明的祖先元素生效。在你想查询其大小的元素上设置该属性(如需定位某个特定的祖先,还可选择添加 container-name):
.my-component {
container-type: inline-size;
container-name: my-component;
}
然后,在文件顶部添加 @use "lib/container";,并按照与 lib/viewport 相同的方式使用 mixin:
@use "lib/container";
.my-component {
container-type: inline-size;
container-name: my-component;
@include container.until(sm, my-component) {
// SCSS rules here will be applied when
// .my-component itself is narrower than
// the sm breakpoint
}
}
$name 参数是可选的。如果作用域内只有一个可查询的容器,可将其省略;当你需要定位某个特定的具名容器时再传入(例如,当规则写在某个后代元素上,而非容器元素本身时)。
实际示例请查看 app/assets/stylesheets/admin/dashboard/engagement.scss 中的 .db-whos-posting,它设置了 container-type: inline-size; container-name: db-whos-posting; 并使用 container.until(sm, db-whos-posting),以便独立于视口调整自身布局。
另请参阅
- 为不同设备设计(触摸和悬停),介绍如何检测触摸/悬停能力,以及旧版移动/桌面模式。
- 使用 BEM 的 CSS 类准则,介绍 CSS 类命名约定。
谢谢你的反馈!