Search code examples
imageoptimizationvuejs3nuxt.jsnuxt3.js

Optimizing Background Images In Nuxt 3


I'm developing a Nuxt.js application and I need to set a decorative background image for a <div>. I prefer using background-image for decorative elements, as it is semantically more appropriate, while using <img> tags for content images. <NuxtImg> results in an optimized <img>, but I would like to optimize background-images.


Solution

  • You can use the useImage() to generate a helper function as described in the documentation

    This will allow you to get an optimized image generation same way as NuxtImg tag, but returning just the url.

    const img = useImage()
    const backgroundStyles = computed(() => {
      const imgUrl = img('https://github.com/nuxt.png', { width: 100 })
      return { backgroundImage: `url('${imgUrl}')` }
    })