I have two tips for you for creating utilities or component classes.
- Separate your
@applystatements - Prevent specificity wars
Separate your apply statements
Unlike HTML, Tailwind does not require you to put all of your utilities into a single line in the CSS. So you can split them up into multiple lines and make them more readable.
Here’s what it might look like:
.article { header { @apply vertical gap-4; }
.meta { @apply vertical gap-0.5; @apply june; @apply text-7 bp8:text-8; --font-style: 60; }}In this example, you can see that I grouped similar things together:
verticalandgapare closely related so they’re together.juneis a font family so I placed it by itself.text-7andtext-8control the size of the text, placed in the same line so I can immediately tell thefont-sizewill change at800px.
Preventing specificity wars
If you are building libraries, you will notice that all of the “components” you build with @utility will fall into the utility layer. This happens because Tailwind puts all utilities in that layer. There’s no way to control it.
So if you’re building a library and you want to prevent specificity wars for your users, you need to reduce the specificity of your selectors by using :where. (It prevents any further specificity from being added to the selector).
By default, the minimum selector strength is [0, 1, 0] (1 class), so any utility used in the HTML will automatically overwrite the component.
Here’s an example:
@utility tablist-left { --placement: left; display: flex; flex-flow: column nowrap;
/* This allows users to overwrite the `tab` properties with a utility class in the HTML, without needing !important */ :where(.tab) { align-self: stretch; justify-content: left; }}Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson