Learn Nuxt · 7/12

Styling and Assets: Making It Look Good

7 min read

Styling and Assets: Making It Look Good 🎨

Welcome! Let's dive into making your Nuxt applications not just functional, but also visually appealing. Managing styles, images, and fonts is a crucial part of web development. Get it wrong, and your site can feel like a cluttered garage sale. Get it right, and you provide a smooth, pleasant experience for your users.

In this guide, we'll explore how Nuxt helps you organize your assets and styling in a clean and efficient way.


1. The Assets vs Public Directory 📂

The Problem: Where do you put your static files like images, fonts, and stylesheets? If you just dump them anywhere, you'll create a maintenance nightmare. You also need a way to tell Nuxt whether these files need to be processed and optimized or just served as-is.

The Solution: Nuxt provides two special directories to handle this: assets and public. Understanding the difference is key to a well-organized project.

Imagine you're preparing a meal. Some ingredients need to be chopped, seasoned, and cooked before they're ready to be served (your assets directory). Other ingredients, like a bottle of ketchup, are ready to be put on the table just as they are (your public directory).

The assets Directory

Files in the assets directory are processed by your build tool (like Vite or Webpack). This means they can be optimized, minified, and have their filenames hashed for better caching. This is the place for files that are part of your site's source code and benefit from build-time optimizations.

  • What to put here:
    • CSS pre-processor files (Sass, Less)
    • Unoptimized images that need compression
    • Fonts that you want to be processed

How to use it: When you reference a file from the assets directory in your components or CSS, you use a relative path.

vue
<template>
  <!-- Nuxt's build tool will process this image -->
  <img src="~/assets/logo.png" alt="My awesome logo">
</template>

<style>
body {
  /* The URL will be transformed during the build process */
  background-image: url('~/assets/background.jpg');
}
</style>

Under the hood, Nuxt will process logo.png, maybe compress it, and give it a unique filename like logo.a87fg5.png to prevent caching issues when you update the image.

✨ Fun Fact: The ~ symbol is an alias for the root directory of your project. It's a handy shortcut so you don't have to write ../../assets/image.png.

The public Directory

Files in the public directory are not processed by the build tool. They are simply copied to the root of your built project as-is. This is perfect for files that must have a specific name or that don't need any processing.

  • What to put here:
    • robots.txt
    • favicon.ico
    • Files that are referenced by external scripts

How to use it: You reference these files from the root of your site, using a /.

vue
<template>
  <!-- This file is served directly from the public directory -->
  <img src="/icon.png" alt="An icon">
</template>

2. Global CSS and Scoped Styles 🎨

The Problem: How do you apply consistent styles across your entire application without having them leak and unintentionally affect other components? You want a nice, uniform theme, but you don't want the button style you wrote for your homepage to mess up the buttons in your user dashboard.

The Solution: Nuxt allows you to define global styles for your whole application and also lets you write styles that are "scoped" to a single component.

Global CSS

To apply styles globally, you can create a main CSS file and register it in your nuxt.config.ts. This is perfect for defining your overall look and feel, like fonts, colors, and basic element styles.

  1. Create a CSS file: Let's create a file at assets/css/main.css.

    css
    /* assets/css/main.css */
    body {
      font-family: 'Arial', sans-serif;
      background-color: #f0f2f5;
      color: #333;
    }
    
    a {
      color: #007bff;
      text-decoration: none;
    }
  2. Add it to your Nuxt config:

    typescript
    // nuxt.config.ts
    export default defineNuxtConfig({
      css: [
        '~/assets/css/main.css',
      ],
    })

Now, these styles will be applied to every page of your application. Easy peasy.

Scoped Styles

To create styles that only apply to a single component, you can add the scoped attribute to the <style> tag within your .vue file. This prevents your styles from "leaking out" and affecting other components.

Example: Let's create a Button.vue component.

vue
<template>
  <button class="awesome-button">Click Me!</button>
</template>

<style scoped>
/* These styles will ONLY apply to elements within this component */
.awesome-button {
  background-color: #28a745;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.awesome-button:hover {
  background-color: #218838;
}
</style>

Because of the scoped attribute, the .awesome-button class will not affect any other button on your site unless it's an instance of this specific Button.vue component. Nuxt achieves this by adding a unique data attribute to your component's HTML elements and your CSS selectors during the build process.


3. Integrating Tailwind CSS via Nuxt Modules 💨

The Problem: Writing custom CSS for every single element can be time-consuming and lead to a bloated CSS file. You need a faster way to build modern-looking UIs without reinventing the wheel every time you need to style a div.

The Solution: Use a utility-first CSS framework like Tailwind CSS. Nuxt has a fantastic module system that makes integrating tools like Tailwind incredibly simple.

A Nuxt module is like a plugin that can extend Nuxt's core functionality. The Nuxt Tailwind module sets up everything you need to start using Tailwind's utility classes right away.

Setup and Installation

Getting started with the Nuxt Tailwind module is a breeze.

  1. Install the module:

    bash
    # Using pnpm
    pnpm add -D @nuxtjs/tailwindcss
    
    # Using yarn
    yarn add -D @nuxtjs/tailwindcss
    
    # Using npm
    npm install -D @nuxtjs/tailwindcss
  2. Add it to your nuxt.config.ts: The Nuxt CLI will usually offer to do this for you. If not, add it manually.

    typescript
    // nuxt.config.ts
    export default defineNuxtConfig({
      modules: [
        '@nuxtjs/tailwindcss'
      ]
    })

And... that's it! You're ready to go. You can now start using Tailwind's utility classes in your components.

vue
<template>
  <div class="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-md flex items-center space-x-4">
    <div class="flex-shrink-0">
      <img class="h-12 w-12" src="/logo.svg" alt="ChitChat Logo">
    </div>
    <div>
      <div class="text-xl font-medium text-black">ChitChat</div>
      <p class="text-gray-500">You have a new message!</p>
    </div>
  </div>
</template>

This approach allows for rapid prototyping and development, as you can style elements directly in your HTML without constantly switching to a separate CSS file.


4. Handling Images and Fonts Efficiently 🖼️

The Problem: Large, unoptimized images and fonts are one of the biggest causes of slow websites. You need a way to serve these assets efficiently to ensure a fast and smooth user experience.

The Solution: Nuxt helps you handle these assets correctly, but it's important to follow best practices for optimization.

Images

As we learned, you can place images in either the assets or public directory.

  • Use assets for core site images: For images that are part of your site's design (logos, backgrounds, icons), put them in assets. They will be optimized by the build process.

    vue
    <template>
      <img src="~/assets/images/hero-image.jpg" alt="A hero image">
    </template>
  • Use public for user-uploaded content or dynamic images: If you have images that come from a CMS or are uploaded by users, the public directory is a good choice, as they don't need to go through the build process. However, you should consider using an image optimization service or a Nuxt image module for these cases to serve them in modern formats (like WebP) and correctly sized.

Local Fonts

Using custom fonts can give your site a unique personality. To handle them efficiently:

  1. Place font files in the assets directory: Create a fonts folder inside assets and add your font files (e.g., .woff2).

  2. Define @font-face in your global CSS: In your assets/css/main.css, define your custom font family.

    css
    /* assets/css/main.css */
    @font-face {
      font-family: 'MyCustomFont';
      src: url('~/assets/fonts/my-custom-font.woff2') format('woff2');
      font-weight: normal;
      font-style: normal;
      font-display: swap; /* Important for performance! */
    }
    
    body {
      font-family: 'MyCustomFont', sans-serif;
    }

The font-display: swap; property is a game-changer. It tells the browser to display text immediately with a fallback font and then "swap" in your custom font once it has loaded. This prevents the dreaded "invisible text" problem on slow connections.

By following these conventions, you can keep your project tidy and your website performing at its best. Happy styling! ✨


Further Reading & References

Challenge

Challenge Instructions

You are tasked with correctly configuring styles, fonts, and assets for a Nuxt application. You will be working with a simulated nuxt.config.ts file, a global stylesheet, and a Vue component named UserProfile.vue.

Complete the following tasks based on modern Nuxt practices:

  1. In the nuxt.config.ts configuration, register the @nuxtjs/tailwindcss module.
  2. Also in nuxt.config.ts, add the path ~/assets/css/global.css to the css array to apply it globally.
  3. In the section representing the content of assets/css/global.css, define a @font-face rule. The font family should be Inter, its source URL should point to ~/assets/fonts/Inter.woff2, and you must include font-display: swap; for better perceived performance.
  4. In the same global CSS section, add a style rule for the body element. Set its background-color to #f0f2f5 and apply the Inter font, with sans-serif as a fallback.
  5. In the UserProfile.vue component, update the <img> tag's src attribute to correctly reference an image located at assets/images/avatar.png.
  6. Finally, add a scoped style block to the UserProfile.vue component to ensure its styles do not leak globally. Inside this block, target the .username class and set its color to #1d2129 and font-size to 18px.

Expected result

Your final code should consist of three completed sections:

  1. nuxt.config.ts: The modules array should contain the string '@nuxtjs/tailwindcss', and the css array should contain the string '~/assets/css/global.css'.

  2. assets/css/global.css: This section should contain a complete @font-face rule for the 'Inter' font family, with its src property pointing to the correct font file and font-display set to swap. It should also contain a body selector with the background-color and font-family properties correctly set.

  3. components/UserProfile.vue: The <img> tag's src attribute should be set to ~/assets/images/avatar.png. The component must include a <style scoped> tag containing a CSS rule for the .username class with the specified color and font-size.

javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.