Nuxt应用引入tailwindcss后标题(h1 h2等)样式失效问题 2024-06-20

1. 问题描述

Nuxt应用引入tailwindcss后,所有的h1到h6的样式消失了。效果如下:

问题效果页

2. 问题原因

原因是tailwindcss对这些样式做了预处理,见如下:
https://tailwindcss.com/docs/preflight

网上也有人问过这个问题:
https://stackoverflow.com/questions/70892781/how-do-h1-text-became-smaller-when-i-used-tailwind-css

官方描述如下:All heading elements are completely unstyled by default, and have the same font-size and font-weight as normal text. 样式变成了:

h1,
h2,
h3,
h4,
h5,
h6 {
  font-size: inherit;
  font-weight: inherit;
}

3. 如何解决

知道了问题产生的原因,那就好解决了。主要有两种方法:

3.1 去掉预处理

tailwind.config.ts 做如下配置

module.exports = {
  corePlugins: {
    preflight: false,
  }
}

3.2 引入tailwindcss-typography

另一种方法是引入 tailwindcss-typography 这个包

pnpm install @tailwindcss/typography 

具体使用见:
https://github.com/tailwindlabs/tailwindcss-typography

需要在tailwind.config.ts做如下配置

/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    // ...
  },
  plugins: [
    require('@tailwindcss/typography'),
    // ...
  ],
}

同时在所在的页面div 里添加 prose 这个 class

4. 问题解决

问题解决,第二种方法稍微复杂一些。解决后,页面正常如下:


解决后页面
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容