You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Tailwind CSS的lvh、svh等新长度类型添加回退属性?

问题:让Tailwind CSS导出带回退属性的dvh/svh/lvh样式

我在tailwind.config.js中配置了新的CSS长度类型(dvh/svh/lvh):

module.exports = {
  theme: {
    extend: {
      height: {
        "screen": "100dvh",
        "screen-small": "100svh",
        "screen-large": "100lvh"
      }
    }
  }
}

配置后生成的CSS只有单一属性:

.h-screen {
    height: 100dvh;
}

但我希望生成带回退属性的CSS,兼容Opera、IE等旧浏览器:

.h-screen {
  height: 100vh; /* 为Opera、IE等浏览器提供回退 */
  height: 100dvh;
}

请问有没有合适的方法让Tailwind CSS导出这种带回退属性的样式?

解决方案

有两种简单的方法可以实现这个需求:

方法一:在主题配置中使用数组指定多值

Tailwind CSS支持在配置的属性值中传入数组,数组中的每一项会被转换为对应的CSS声明(后面的声明会覆盖前面的,符合CSS层叠规则)。直接修改你的tailwind.config.js:

module.exports = {
  theme: {
    extend: {
      height: {
        // 先指定回退值,再指定目标值
        "screen": ["100vh", "100dvh"],
        "screen-small": ["100vh", "100svh"],
        "screen-large": ["100vh", "100lvh"]
      }
    }
  }
}

这样生成的CSS会自动包含两个height属性,顺序和数组一致,正好满足回退需求。

方法二:通过自定义插件添加工具类

如果需要更灵活的控制(比如自定义前缀等),可以通过Tailwind插件的addUtilities方法手动定义工具类:

module.exports = {
  theme: {
    // 保留原有的其他主题配置
    extend: {}
  },
  plugins: [
    function({ addUtilities }) {
      addUtilities({
        '.h-screen': {
          'height': '100vh',
          'height': '100dvh',
        },
        '.h-screen-small': {
          'height': '100vh',
          'height': '100svh',
        },
        '.h-screen-large': {
          'height': '100vh',
          'height': '100lvh',
        }
      })
    }
  ]
}

注意:如果需要在生成的CSS中添加注释,仅靠Tailwind本身无法实现,需要搭配PostCSS插件(如postcss-comment)来处理注释语法。

内容的提问来源于stack exchange,提问作者Hiroki Yokoiwa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:16:21