Skip to content
全部文档

aspect-ratio

用于控制元素宽高比的工具类。

快速参考

属性
aspect-<ratio>aspect-ratio: <ratio>;
aspect-squareaspect-ratio: 1 / 1;
aspect-videoaspect-ratio: var(--aspect-video); /* 16 / 9 */
aspect-autoaspect-ratio: auto;
aspect-(<custom-property>)aspect-ratio: var(<custom-property>);
aspect-[<value>]aspect-ratio: <value>;

示例

基础示例

使用 aspect-<ratio> 等工具类(如 aspect-3/2)为元素指定宽高比:

html
<!-- [!code classes:aspect-3/2] -->
<img class="aspect-3/2 object-cover ..." src="/img/villas.jpg" />

使用视频宽高比

使用 aspect-video 工具类为视频元素设置 16 / 9 宽高比:

html
<!-- [!code classes:aspect-video] -->
<iframe class="aspect-video ..." src="https://www.youtube.com/embed/dQw4w9WgXcQ"></iframe>

使用自定义值

使用 aspect-[<value>] 等工具类,根据完全自定义的值设置宽高比:

html
<img class="aspect-[calc(4*3+1)/3] ..." />

对于 CSS 变量,也可以使用 aspect-(<custom-property>) 语法:

html
<img class="aspect-(--my-aspect-ratio) ..." />

这只是 aspect-[var(<custom-property>)] 的简写,会自动为你加上 var() 函数。

响应式设计

使用 md: 等断点变体作为 aspect-ratio 工具类的前缀,即可仅在中等及以上屏幕尺寸下应用该工具类:

html
<iframe class="aspect-video md:aspect-square ..."></iframe>

了解如何使用变体,请参阅变体文档

自定义主题

使用 --aspect-* 主题变量来自定义项目中的宽高比工具类:

css
@theme {
  --aspect-retro: 4 / 3;
}

现在可以在标记中使用 aspect-retro 工具类:

html
<iframe class="aspect-retro"></iframe>

了解如何自定义主题,请参阅主题文档

文档译文以 MIT 协议授权;原文版权归 Tailwind Labs。湘ICP备2026005453号-2