Tailwind CSS h-52/w-52解析错误:设置52px却生成13rem
解决Tailwind CSS中w-52/h-52解析为13rem而非52px的问题
问题说明
搭建Tailwind极简项目时,给div设置bg-emerald-500 w-52 h-52类,预期宽高为52px,但实际渲染为208px×208px。生成的CSS显示.h-52和.w-52对应的height/width值为13rem。
原因与修复方法
原因
Tailwind默认的尺寸类(如w-{n}、h-{n})基于间距系统:1个单位等于0.25rem(即4px),因此w-52计算为52×4px=208px,换算成rem就是13rem(1rem=16px),这是框架默认行为,并非bug。
修复方式
方式一:使用任意值类(适合一次性需求)
直接在类名中指定像素值,格式为w-[52px]和h-[52px],修改HTML代码:
<div class="bg-emerald-500 w-[52px] h-[52px]"></div>
无需修改配置,编译后会直接生成对应52px的样式。
方式二:扩展自定义尺寸(适合重复使用)
在tailwind.config.js的theme.extend中添加自定义尺寸配置:
/** @type {import('tailwindcss').Config} */ module.exports = { content: ['./build/*.html'], theme: { extend: { // 单独定义宽高 width: { '52px': '52px', }, height: { '52px': '52px', }, // 或用size同时定义宽高(更简洁) // size: { // '52px': '52px', // }, }, }, plugins: [], }
修改配置后重启Tailwatch命令,即可在HTML中使用w-52px和h-52px类:
<div class="bg-emerald-500 w-52px h-52px"></div>
原项目相关文件信息
文件结构
tailwind build css styles.css index.html src input.css tailwind.config.js
原index.html代码
<!DOCTYPE html> <html lang="en"> <head> <title>Tailwind Experiment</title> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <div class="bg-emerald-500 w-52 h-52"></div> </body> </html>
生成的CSS片段
... .h-52 { height: 13rem; } .w-52 { width: 13rem; } ...
原input.css代码
@tailwind base; @tailwind components; @tailwind utilities;
原tailwind.config.js代码
/** @type {import('tailwindcss').Config} */ module.exports = { content: ['./build/*.html'], theme: { extend: {}, }, plugins: [], }
编译命令
npx tailwindcss -i ./src/input.css -o ./build/css/style.css --watch
内容的提问来源于stack exchange,提问作者Jillian Hoenig
相关产品推荐
相关产品推荐

