平滑扩缩

Web 功能: 容器查询(大小)

概览

平滑扩缩允许组件根据其当前尺寸调整其内部比例(例如字体大小和间距)。与在固定断点之间跳转相比,这样可以打造更具凝聚力的设计。

过去,平滑扩缩是通过视口单位(基于屏幕尺寸进行缩放)实现的,而现代容器查询单位则允许组件相对于其父级容器进行缩放。这可确保组件无论放置在布局中的哪个位置,都能呈现良好的视觉效果,从而提高组件的隔离性和可重用性。

实现

1. 定义容器

如需使用容器查询单位,您必须先在父元素上定义包含上下文。

.component-wrapper {
  /* Define the container type. Use 'inline-size' for width-based scaling. */
  /* You can also use 'size' for both width and height, but it requires explicit sizing. */
  container-type: inline-size;
  
  /* Optional: Name the container for specific targeting */
  container-name: fluid-card;
}

2. 使用容器查询单位

使用容器查询单位(cqi、cqb 等)设置相对于容器尺寸的大小。

  • cqi:容器内嵌大小(水平书写模式下的宽度)的 1%。
  • cqb:容器块大小(水平书写模式下的高度)的 1%。

注意:容器单位可以直接用于任何属性,而无需 @container 查询规则。它们会根据具有已定义 container-type 的最近祖先实体自动解析。

.component-title {
  /* Scale font size based on container width */
  /* 10cqi means 10% of the container's width */
  font-size: 10cqi;
}

.component-body {
  /* Scale padding based on container width */
  padding: 5cqi;
}

3. 使用 clamp() 限制值

为防止尺寸过小或过大,请使用 CSS clamp() 函数。这会影响用户缩放或调整基本字体大小的能力。为确保文本符合无障碍指南,最大字号不得超过最小字号的 2.5 倍。

.component-title {
  /* Clamp font size between 1rem and 2.5rem, scaling with 5% of container width */
  font-size: clamp(1rem, 5cqi, 2.5rem);
}

后备策略

如果浏览器不支持容器查询,您应使用视口单位或标准媒体查询提供后备方案。

.component-title {
  /* Fallback for browsers that do not support container units */
  font-size: clamp(1rem, 5vw, 2.5rem);
}

@supports (font-size: 1cqi) {
  .component-title {
    /* Use container units where supported */
    font-size: clamp(1rem, 5cqi, 2.5rem);
  }
}

此后备方案可确保文本仍会缩放,但会基于屏幕宽度而非组件宽度。您应测试此功能,以验证它是否适用于您的用例。