rocambille
rocambille

Reputation: 15956

How to set lang attribute on html element with Nuxt?

Using the file nuxt.config.js file, head contents can be customized to add some meta, or other things:

module.exports = {
  /*
  ** Headers of the page
  */
  head: {
    title: 'awesome title',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Nuxt.js project' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  ...
}

But I can't find anything in the documentation to set attributes on the html element -- I want to set the lang attribute. Is there a way to do that?

Upvotes: 64

Views: 45634

Answers (4)

Jarmos
Jarmos

Reputation: 456

For Nuxt 3 and above, I recommend the following approach by utilising the useHead() builtin composable (see the docs) instead.

Here's an example app.vue file (which is the root component Nuxt uses to render the SPA).

<template>
  <main>
    <NuxtPage />
  </main>
</template>

<script setup lang="ts">
useHead({
  htmlAttrs: {
    lang: "en",
  },
});
</script>

This way your code will be bloat free due to less configurations introduced to the nuxt.config.ts file and also hacking through it as recommended in the previous older answers.

Upvotes: 3

yuriy636
yuriy636

Reputation: 11661

Source: Declaring language in HTML tag · Issue #388 · nuxt/nuxt.js

head supports a htmlAttrs property. It will map each key:value of the object as attribute:value

module.exports = {
  head: {
    htmlAttrs: {
      lang: 'en'
    }
  }
}

How to do this when using i18n: Setting the language attribute when using i18n and Nuxt?

Upvotes: 120

bilal
bilal

Reputation: 296

Add htmlAttrs to nuxt.config.js

export default defineNuxtConfig({
    app: {
        head: {
            htmlAttrs: {
                lang: 'en',
            },
            title: 'title',
            charset: 'utf-8',
            meta: [],
            link: [],
        }
    },
})

Upvotes: 15

Daniel
Daniel

Reputation: 8647

In Nuxt 3 type in the component

<script setup>
useHead({
  htmlAttrs: {
    lang: 'en',
    style: 'font-size: 13px'
  }
})
</script>

https://v3.nuxtjs.org/getting-started/seo-meta/

Upvotes: 23

Related Questions