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

Tailwind CSS中自定义类font-size与text-3xl共存时失效的原因及解决方法

问题原因

这是CSS优先级与样式加载顺序共同导致的问题:

  • Tailwind的text-3xl和你的.myclass都是类选择器,优先级完全相同。
  • Tailwind CDN脚本会动态生成样式并插入到<head>的末尾,而你的自定义<style>标签放在了</head>之后,导致Tailwind的样式声明顺序在自定义样式之后。根据CSS“后声明的样式覆盖先声明同优先级样式”的规则,text-3xl的字体大小(1.875rem)会覆盖.myclass的10rem设置。
解决方案

以下是几种可行的解决方法,按推荐程度排序:

1. 使用Tailwind @layer指令(推荐)

将自定义样式放入Tailwind的utilities或components层,Tailwind会自动处理样式优先级,让自定义样式覆盖默认工具类:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    @layer utilities {
      .myclass {
        font-size: 10rem;
      }
    }
  </style>
</head>
<body>
  <h1 class="myclass text-3xl font-bold underline">
    Hello world!
  </h1>
</body>
</html>

2. 提升自定义样式优先级

通过组合选择器(比如元素选择器+类选择器)让.myclass的优先级高于单纯的类选择器text-3xl:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<style>
  h1.myclass {
    font-size: 10rem;
  }
</style>
<body>
  <h1 class="myclass text-3xl font-bold underline">
    Hello world!
  </h1>
</body>
</html>

3. 调整样式加载顺序

把自定义<style>标签移到<head>内部,且放在Tailwind脚本之后,确保自定义样式的声明顺序在Tailwind样式之后:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    .myclass {
      font-size: 10rem;
    }
  </style>
</head>
<body>
  <h1 class="myclass text-3xl font-bold underline">
    Hello world!
  </h1>
</body>
</html>

4. 使用!important(不推荐)

仅在应急场景下使用,通过!important强制覆盖同优先级样式:

.myclass {
  font-size: 10rem !important;
}

内容的提问来源于stack exchange,提问作者Moosa Imran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:08:25