响应式设计
了解如何使用 Chakra UI 内置的响应式样式属性创建响应式设计
概述
¥Overview
响应式设计是现代 Web 开发的一个基本方面,它允许网站和应用无缝适应不同的屏幕尺寸和设备。
¥Responsive design is a fundamental aspect of modern web development, allowing websites and applications to adapt seamlessly to different screen sizes and devices.
Chakra 使用移动优先断点系统,并在你编写响应式样式时利用最小宽度媒体查询 @media(min-width)
。
¥Chakra uses a mobile-first breakpoint system and leverages min-width media
queries @media(min-width)
when you write responsive styles.
Chakra 默认提供五个断点:
¥Chakra provides five breakpoints by default:
const breakpoints = {
base: "0rem", // 0px
sm: "30rem", // ~480px
md: "48rem", // ~768px
lg: "62rem", // ~992px
xl: "80rem", // ~1280px
"2xl": "96rem", // ~1536px
}
对象语法
¥Object syntax
以下是如何在大屏幕上更改文本字体粗细的示例。
¥Here's an example of how to change the font weight of a text on large screens
<Text fontWeight="medium" lg={{ fontWeight: "bold" }}>
Text
</Text>
或使用基于 prop 的修饰符
¥or use the prop based modifier
<Text fontWeight={{ base: "medium", lg: "bold" }}>Text</Text>
数组语法
¥Array syntax
Chakra 还接受数组作为响应式样式的值。将数组中每个断点的相应值传递给 组件。以我们之前的代码为例:
¥Chakra also accepts arrays as values for responsive styles. Pass the corresponding value for each breakpoint in the array. Using our previous code as an example:
<Text fontWeight={["medium", undefined, undefined, "bold"]}>Text</Text>
注意使用 undefined
作为断点来跳过 md
和 lg
断点。
¥Notice the use of undefined
for the breakpoints to skip the md
and lg
breakpoints.
断点定位
¥Breakpoint targeting
断点范围
¥Breakpoint range
Chakra 提供了一种使用 To
符号定位一系列断点的方法。要在 md
和 xl
断点之间应用样式,请使用 mdToXl
属性:
¥Chakra provides a way to target a range of breakpoints using the To
notation.
To apply styles between the md
and xl
breakpoints, use the mdToXl
property:
<Text fontWeight={{ mdToXl: "bold" }}>Text</Text>
此文本仅在 md
到 xl
断点处显示为粗体。
仅断点
¥Only breakpoint
要定位单个断点,请使用 Only
符号。以下是如何使用 lgOnly
属性仅在 lg
断点应用样式的示例:
¥To target a single breakpoint, use the Only
notation. Here's an example of how
to apply styles only in the lg
breakpoint, using the lgOnly
property:
<Text fontWeight={{ lgOnly: "bold" }}>Text</Text>
在断点处隐藏元素
¥Hiding elements at breakpoint
Chakra 提供 hideFrom
和 hideBelow
实用程序,用于在特定断点处隐藏元素。
¥Chakra provides the hideFrom
and hideBelow
utilities to hide elements at
specific breakpoints.
要隐藏 md
断点下方的元素,请使用 hideFrom
实用程序:
¥To hide an element from the md
breakpoint, use the hideFrom
utility:
<Stack hideFrom="md">
<Text>This text will be hidden from the `md` breakpoint</Text>
</Stack>
要隐藏 md
断点下方的元素,请使用 hideBelow
实用程序:
¥To hide an element below the md
breakpoint, use the hideBelow
utility:
<Stack hideBelow="md">
<Text>This text will be hidden below the `md` breakpoint</Text>
</Stack>
自定义断点
¥Customizing Breakpoints
要了解如何自定义断点,请参阅 自定义断点 部分。
¥To learn how to customize breakpoints, please refer to the customizing breakpoints section.
FAQs
为什么断点会转换为 rem
?
¥Why are breakpoints converted to rem
?
转换为 rem
是有意为之,并且有利于可访问性:
¥The conversion to rem
is intentional and beneficial for accessibility reasons:
-
用户更改了浏览器的字体设置
-
用户放大
-
HTML 中的字体大小已更改