使用 CSS 的 if() 和 clamp() 实现更智能的流体排版
Fluid typography—the idea that text scales smoothly with screen size—has evolved alongside CSS itself. Before modern functions existed, developers often relied on verbose media queries and manual breakpoints. The introduction of clamp() simplified this work by allowing text to grow with viewport width while still respecting minimum and maximum limits. Now, with the arrival of the CSS if() function in Chrome, it becomes possible to refine these rules further, introducing conditional logic directly in CSS without additional classes or JavaScript.
流体排版——即文本随屏幕尺寸平滑缩放——随着 CSS 本身的发展而演进。在现代函数出现之前,开发者通常依赖冗长的媒体查询和手动断点。clamp() 的引入简化了这项工作,让文本可以随视口宽度增长,同时仍遵守最小和最大限制。现在,随着 CSS if() 函数在 Chrome 中的到来,可以进一步细化这些规则,直接在 CSS 中引入条件逻辑,而无需额外的类或 JavaScript。
The clamp() function works by defining three values: a minimum, a preferred (scalable) value, and a maximum. For example:
clamp() 函数通过定义三个值来工作:最小值、首选(可缩放)值和最大值。例如:
font-size: clamp(16px, 2vw + 16px, 24px);
font-size: clamp(16px, 2vw + 16px, 24px);
font-size: clamp(16px, 2vw + 16px, 24px);
This ensures the font size never drops below 16 px, grows with 2vw as the screen widens, and stops at 24 px. The challenge is that not all text elements should scale at the same rate. Headings, for instance, often benefit from a faster scale, while body copy should remain more stable for readability.
这确保了字体大小不会低于 16 px,会随着屏幕变宽按 2vw 增长,并在 24 px 处停止。挑战在于并非所有文本元素都应以相同速率缩放。例如,标题通常受益于更快的缩放,而正文则应保持更稳定以确保可读性。
This is where if() enters the picture. It lets you test conditions inline—such as which type of text is being styled—and choose different scaling factors. Combined with a custom function, it becomes straightforward to reuse across a stylesheet.
这就是 if() 登场的地方。它允许你在行内测试条件——例如正在设置样式的文本类型——并选择不同的缩放因子。结合自定义函数后,在整个样式表中复用就变得非常简单。
A custom function can package up the logic into a clean, reusable form. Here is an example:
自定义函数可以将逻辑打包成简洁、可复用的形式。示例如下:
@function --fluid-type(--font-min, --font-max, --type: 'header') { --scalar: if(style(--type: 'header'): 4vw; style(--type: 'copy'): 0.5vw; else: 1vw); result: clamp...