You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt中为HTML元素设置lang属性?

How to set the lang attribute on the HTML element in Nuxt.js?

Question

I know we can customize page head content and add metadata via the nuxt.config.js file, like this example:

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 couldn't find any documentation on setting attributes for the HTML element. Is there a way to set the lang attribute for the HTML tag?


Answer

Great question! You absolutely can set the lang attribute on the root HTML element in Nuxt.js, and it’s simpler than you might think. The head object in your nuxt.config.js supports an htmlAttrs property specifically for adding attributes to the <html> tag.

Here’s how to implement it:

  • Inside the head configuration block, add an htmlAttrs object.
  • Within that object, define the lang key with your target language code (e.g., 'en' for English, 'es' for Spanish).

Static Language Example

module.exports = {
  head: {
    title: 'awesome title',
    // Add this section to set static lang attribute
    htmlAttrs: {
      lang: 'en'
    },
    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' }
    ]
  },
  // ... other Nuxt config options
}

This will render your HTML root tag like this:

<html lang="en">
  <!-- Your page content here -->
</html>

If you’re working on a multilingual site and need dynamic language switching, you can also define htmlAttrs as a function in your layouts or page components. This lets you access the app context to pull the current locale (for example, if you’re using Nuxt’s i18n module):

Dynamic Language Example

// In your default layout file (layouts/default.vue)
export default {
  head({ app }) {
    return {
      htmlAttrs: {
        lang: app.i18n.locale
      }
    }
  }
}

This way, the lang attribute will update automatically whenever the user switches languages on your site.


内容的提问来源于stack exchange,提问作者rocambille

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:05:11