DEV Community

jboada
jboada

Posted on • Updated on

Nuxt 3, UnoCSS, and Preset rem to px

Hello everybody! πŸ‘‹

This post is about generating px units by default in UnoCSS when used in Nuxt 3.


Preamble

Working on a project that uses Nuxt 3 and Vuetify; UnoCSS was the choice to handle the CSS tweaks/adjustments because it offers many advantages in the Utility Classes engines/frameworks universe.

UnoCSS and length units: a little bump in the road for the project?

However, there was one thing: UnoCSS generates rem units for length units by default if a length unit is not indicated. What does this mean? Let's see the following example:

If m-2 is used (a length unit is NOT indicated) either as an attribute or CSS class in an HTML element, UnoCSS would generate the following CSS class:

.m-2 {
  margin: 0.5rem;
}
Enter fullscreen mode Exit fullscreen mode

Now, if m-8px is used (a length unit IS indicated) either as an attribute or CSS class in an HTML element, UnoCSS would generate the following CSS class:

.m-8px {
  margin: 8px;
}
Enter fullscreen mode Exit fullscreen mode

Solution

To achieve the goal of generating px units by default in UnoCSS, the @unocss/preset-rem-to-px package was used because its purpose is to convert the rem units to px units.


Installation guide for the @unocss/preset-rem-to-px package in Nuxt 3

Follow this installation guide to install and configure the @unocss/preset-rem-to-px package in Nuxt 3:

Step 1. Install @unocss/preset-rem-to-px

npm i -D @unocss/preset-rem-to-px
Enter fullscreen mode Exit fullscreen mode

Step 2. Add the following references to the nuxt.config.ts file:

...
import presetUno from "@unocss/preset-uno";
import presetRemToPx from "@unocss/preset-rem-to-px";
import presetAttributify from "@unocss/preset-attributify";
import presetIcons from "@unocss/preset-icons";
...
Enter fullscreen mode Exit fullscreen mode

Step 3. Add the unocss config to the nuxt.config.ts file this way:

export default defineNuxtConfig({
    ...
    unocss: {
        presets: [
            presetUno(),
            presetAttributify(),
            presetIcons(),
            presetRemToPx(),
        ],
        shortcuts: [],
        rules: [],
    },
    ...
});
Enter fullscreen mode Exit fullscreen mode

You can look at the code in this repo nuxt3-vuetify-unocss at GitHub.

Conclusion

By using the @unocss/preset-rem-to-px package we can achieve the goal of generating px units by default in UnoCSS.


I hope you enjoy this post and find it helpful. If you have any questions or you want to point out some errors, I appreciate it, and I'll do my best to follow up.

If you enjoy it and would like to support me, consider giving a like and sharing it on your favorite social networks.

Stay safe and see you soon! 😎

Top comments (0)