How to Add a Background Image in Next.js?
Last Updated :
24 May, 2024
Next.js is a powerful React framework that allows for server-side rendering and the generation of static websites. Adding a background image to your Next.js application can enhance the visual appeal of your web pages. This article will guide you through the process of adding a background image to a Next.js project.
Prerequisites:
The approaches to add background images in Next.js are mentioned below:
Steps to Create the Next App
Step 1: Create a NextJS application using the following command
npx create-next-app my-app
Step 2: Navigate to the project directory
cd my-app
Project Structure:
.png)
The updated dependencies in package.json file will look like:
"dependencies": {
"next": "14.1.3",
"react": "^18"
}
Using Inline CSS
In this approach we are using inline styling by creating a backgroundImageStyle object that contains CSS properties. Within this object we define a background image specified by a URL and additional styling properties. then we apply this object to a div element using the style attribute which effectively add the background image.
Example: This example uses Inline CSS to add a Background Image in Next.js.
JavaScript
// page.js
export default function Home() {
const backgroundImageStyle = {
backgroundImage: 'url(
https://media.geeksforgeeks.org/wp-content/uploads/20240523121650/React1.png)',
backgroundSize: 'cover',
backgroundPosition: 'center',
height: '100vh',
color: 'white',
margin: 0,
padding: 0,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
};
return (
<div style={backgroundImageStyle}>
<h2>
Adding Background
image Using Inline CSS
</h2>
<h3>
Welcome to GeeksForGeeks
</h3>
</div>
);
}
Step to Run Application: Run the application using the following command from the root directory of the project
npm run dev
Output:

Using External CSS
In this approach, we use an external CSS file to add a Background Image. First, we create a CSS file. In this file, we define a class background-image that have CSS properties such as background-image for specifying the image URL, background-size: cover to ensure the image covers the entire container.
Example: This example uses External CSS to add a Background Image in Next.js.
CSS
/* globals.css */
.background-image {
background-image: url(
'https://learnloner.com/wp-content/uploads/2024/01/DSA.png.webp');
background-size: cover;
background-position: center;
height: 100vh;
text-align: center;
padding: 0;
margin: 0;
justify-content: center;
align-items: center;
color: white;
}
JavaScript
// page.js
// Import the CSS file
import './globals.css';
export default function Home() {
return (
<div className='background-image'>
<h2>
Adding Background image
Using External CSS
</h2>
<h3>
Welcome to GeeksForGeeks
</h3>
</div>
);
}
Step to Run Application: Run the application using the following command from the root directory of the project
npm run dev
Output: