Next.js Image Optimization on Background Images

Photo by bruce mars on Unsplash

Well, I have been loving all of the speed of Next.js, one of the hottest tools out right now for React developers. Next.js 10, which was released just in October 2020 has some impressive image optimization features. The Next.js Image Component is able to preload various image sizes to best fit small viewports, rather than loading a 2000 x 2000 size image on a small iPhone. This has led to improvements to the Largest Contentful Paint(LCP) of websites. The Image Component will also automatically convert images to faster lighter formats on demand! Look up .webp images for more information. Next.js has been working with the Google Chrome Team so watch out!

The Problem

So the Next.js Image Component is awesome. We get it. The problem is that there is no Image Component for background images that are sourced from the stylesheet.

So you can still have background images but they are not automatically optimized. You want optimized images right? I did too. So I found a solution.

My Solution

My solution involved placing an appropriate z-index value to the Image Component in question. Think of z-index like a stack of cards. The higher the number, the higher the element will display on the stack. In my case, I wanted a logo and a search bar to be on top of my background image.

Normally this code would place the image on top of the text and form.

By giving the text and the form a higher z-index value, it stacks them on top of the image like a deck of cards.

This is great for landing pages. Now you can enjoy all the image optimized goodness of Next.js!

Happy Coding :)


Full-Stack Software Engineer and Lifelong Learner