I recently started using UnoCSS in my projects, and I’m really enjoying it.
One of my favourite features is shortcuts
and rules
.
Shortcuts allow us to define a single shorthand for a set of multiple classes. For example, instead of writing class="p-4 m-4 text-red"
, we can write class="card"
.
Rules allow us to define a set of classes that should be applied to a specific element. This is really useful when creating complicated rules.
I created a library, @ryoppippi/unocss-preset
, which includes my opinionated shortcuts and rules.
I’d like to share some of them.
Warning
Using shortcuts that are too short can make your code less readable, so be careful when creating your own shortcuts.
flex
shortcuts
You may have been confused about items-center
and justify-center
before. items-center
is for vertical alignment, and justify-center
is for horizontal alignment. When setting margins, we can use mx-
for horizontal margins and my-
for vertical margins. So, I created a shortcut for flex
based on these naming rules.
const shortcuts = {
fxc: 'flex justify-center',
fxs: 'flex justify-start',
fxe: 'flex justify-end',
fyc: 'flex items-center',
fys: 'flex items-start',
fye: 'flex items-end',
fcc: 'flex items-center justify-center',
};
grid
shortcuts
I also created a shortcut for grid.
You can centre the content using grid
and place-content-center
! This is easy. Additionally, you can use place-items-center
to centre multiple items.
const shortcuts = {
gc: 'grid place-content-center',
gcc: 'gc place-items-center',
};
I’ll add more shortcuts in the future. When I do, I’ll write a new post.
So, see you next time!