Core Concepts

Class & Style Attributes

Introduction

When you need to style your page by adding classes or styles to the <html> or <body> tags, Unhead makes it easy by providing object and array support for the class and style attributes. This allows for both static and reactive styling.

Static Classes & Styles

If your classes or styles aren't going to change, you can provide them as a string.

import { useHead } from '#imports'

useHead({
  htmlAttrs: {
    class: 'my-class my-other-class',
    style: 'background-color: red; color: white;'
  }
})
If you're server-side rendering static tags, you can make use of Bundle Optimizations.

Array Classes & Styles

Using manual separators for classes and styles can be a bit cumbersome, so Unhead allows you to use arrays for both.

import { useHead } from '#imports'

useHead({
  htmlAttrs: {
    class: [
      'my-class',
      'my-other-class'
    ],
    style: [
      'background-color: red',
      'color: white'
    ],
  }
})

Dynamic Classes & Styles

For improved reactivity and merging support, you can provide the class as an object or an array.

Object Syntax for Classes

When providing class as an object, the key should be the class name and the value determines whether the class should be added or not.

import { useHead } from '#imports'

const colorMode = useColorMode()

useHead({
  htmlAttrs: {
    class: {
      // will be rendered when darkMode is true
      dark: () => colorMode.value === 'dark',
      // will be rendered when darkMode is false
      light: () => !colorMode.value === 'dark'
    }
  }
})

Object Syntax for Styles

Similarly, styles can be defined reactively using an object:

import { useHead } from '#imports'

const colorMode = useColorMode()

useHead({
  bodyAttrs: {
    style: {
      // conditional style that only applies when darkMode is true
      'background-color': () => colorMode.value === 'dark' ? 'rgba(0, 0, 0, 0.9)' : false,
      // reactive style that always applies with current value
      'font-size': () => fontSize.value,
    }
  }
})
Did this page help you?