How to Add a Background Image in a CSS File Using Next.js?

To add a background image in a CSS file in Next.js, you need to do the following:

  1. Add Image to the Public Folder:
    • Images that you want to use as background images should be placed in the "public" folder of your Next.js project. This folder is used to serve static files, including images.
    • You can organize your images into sub-folders within the public folder as needed.
  2. Reference Image in CSS Using Base URL:
    • In your CSS file, you can reference the image using its path relative to the public folder.
    • The path should start with a forward slash (/) to indicate that it's rooted at the base URL of your application, which maps to the public folder in Next.js.

For example, if you add your images under the public folder like so:

public/
..└── img/
....└── logo.png

Then you would reference the image in your CSS file in the following way:

.className {
  background-image: url('/img/logo.png');
}

You may also add images directly in the public folder, in which case you would reference it in your CSS like so:

.className {
  background-image: url('/logo.png');
}

This works because Next.js uses the public folder in the root directory to serve static files, like images. The folder name "public" is fixed and cannot be changed. This ensures consistency and proper routing of static assets.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.