tailwindcss 配置默认单位为px

2,909 阅读1分钟

tailwindcss默认支持的rem单位,而不是我们已经非常习惯的px。刚开始使用tailwindcss框架处理项目中的样式时会非常不适应。

如何在项目中使用px单位设置元素的属性?

方法一

tailwindcss 默认支持灵活设置元素距离属性,比如给div加一个16px的内边距,在属性后通过[]来设置具体的px;

<div className="p-[16px]">index</div>

方法二

通过修改 tailwind.config.js 配置文件中的theme属性,比如说我想配置成0 ~ 1000 这个范围内的数字都是px单位,具体配置如下

/** @type {import('tailwindcss').Config} */
module.exports = {
  purge: {
    enabled: false,
    content: ["./src/**/*.{js,jsx,ts,tsx}"],
  },
  content: [],
  theme: {
    spacing: Array.from({ length: 1000 }).reduce((map, _, index) => {
      map[index] = `${index}px`;
      return map;
    }, {}),
    extend: {},
  },
  plugins: [],
};

其他自定义配置

文字font-size单位改成px

module.exports = {
  ...,
  theme: {
    spacing: Array.from({ length: 1000 }).reduce((map, _, index) => {
      map[index] = `${index}px`;
      return map;
    }, {}),
    extend: {
      fontSize: ({ theme }) => ({
        ...theme("spacing"),
      }),
    },
  }
};

在使用text-22 时, 会自动转为22px