rpx arbitrary value color or length unit ambiguity and solution
What is this problem?
Without using weapp-tailwindcss, you can directly write rpx like this:
<div class="text-[32rpx]"></div>
Eventually it will generate css like this:
.text-\[32rpx\] {
color: 32rpx;
}
Why does rpx, a good unit of length, turn into a color?
The reason is that rpx is not a standard W3C length unit specified by CSS. It is an WXSS unit determined by the WeChat applet itself.
What is ambiguity?
Some atomic classes in tailwindcss are ambiguous, such as:
text-[]border-[]bg-[]outline-[]ring-[]
Among them, the css generated by text-[] in text-[16.16px] is font-size: 16.16px;, and the css generated by text-[#123456] is color: #123456;;
This is the ambiguity of atomic classes
And tailwindcss is written for any value with ambiguity:
These will check whether any value within the brackets is a valid CSS length unit!
If it is true, css nodes with length units will be generated, otherwise css nodes with color units will be generated:
/* text-[16px] */
.text-\[16px\] {
font-size: 16px
}
/* text-[#fafafa] */
.text-\[\#fafafa\] {
--tw-text-opacity: 1;
color: rgb(250 250 250 / var(--tw-text-opacity))
}
Then the problem comes. During the unit verification, rpx did not recognize the unit, so the unit was invalid and was assigned to the color group.
/* text-[32rpx] */
.text-\[32rpx\] {
--tw-text-opacity: 1;
color: 32rpx;
}
So it caused this problem! So how to solve it?
Current plug-in solution
The current generation mode of weapp-tailwindcss@5 will process the candidate class names of Tailwind CSS 4 at build runtime to be compatible with the applet unit, and there is no need to execute weapp-tw patch anymore.
If you still see postinstall: "weapp-tw patch" in the old project, you can delete it directly. Currently weapp-tw patch is only a prompt command compatible with older scripts.
Solution to force CSS units
When we use these ambiguous units, we can specify what it should be through the prefix length or color, for example:
<div class="text-[22rpx]">...</div>
<div class="text-[#bada55]">...</div>
<!-- become the following writing method -->
<div class="text-[length:22rpx]">...</div>
<div class="text-[color:#bada55]">...</div>
In this way, the length unit verification is directly skipped through the specified method, and the length unit css is generated!
.text-\[length\:22rpx\] {
font-size: 22rpx
}
You can also use these 2 prefixes to specify the generated form of the css variable:
<!-- generate font-size -->
<div class="text-[length:var(--my-var)]">...</div>
<!-- generate color -->
<div class="text-[color:var(--my-var)]">...</div>
See
- [Add custom style] in
tailwindcss(https://tailwindcss.com/docs/adding-custom-styles#resolving-ambiguities) - Related Issues: #110, #110