Next.js Discord

Discord Forum

How to use background image in nextjs

Answered
Cuban Crocodile posted this in #help-forum
Open in Discord
Avatar
Cuban CrocodileOP
How to use background image in next js from different way?
Answered by Rain infotech
@Cuban Crocodile I would like to propose a solution for the challenge you're facing

1. Using next/image for Background Image:

import Image from 'next/image';

export default function BackgroundImage () {
    return (
        <div className="background-container">
            <Image
                src="/your-background-image.jpg" // Replace with the path to your image
                alt="Background Image"
                layout="fill"
                objectFit="cover"
            />
        </div>
    );
};




2. Create a CSS module(e.g., styles.module.css)

/* styles.module.css */

.backgroundContainer {
    background-image: url("/your-background-image.jpg");
    background-size: cover;
    background-position: center;
    height: 300px;
}

Use the CSS module in your component

import React from 'react';
import styles from './styles.module.css';

export default function BackgroundImage (){
    const backgroundImageUrl = 'https://jpeg.org/images/jpeg-home.jpg';

    return (
    <div className={styles.backgroundContainer}> 
        /* Your component content */
    </div>);
};
View full answer

6 Replies

Avatar
what do you mean different way?
Avatar
Cuban CrocodileOP
I have done it by using . Class name in modulecss but it's not working
Avatar
can you show the code?
and are you using <Image /> or just img tag?
Avatar
@Cuban Crocodile I would like to propose a solution for the challenge you're facing

1. Using next/image for Background Image:

import Image from 'next/image';

export default function BackgroundImage () {
    return (
        <div className="background-container">
            <Image
                src="/your-background-image.jpg" // Replace with the path to your image
                alt="Background Image"
                layout="fill"
                objectFit="cover"
            />
        </div>
    );
};




2. Create a CSS module(e.g., styles.module.css)

/* styles.module.css */

.backgroundContainer {
    background-image: url("/your-background-image.jpg");
    background-size: cover;
    background-position: center;
    height: 300px;
}

Use the CSS module in your component

import React from 'react';
import styles from './styles.module.css';

export default function BackgroundImage (){
    const backgroundImageUrl = 'https://jpeg.org/images/jpeg-home.jpg';

    return (
    <div className={styles.backgroundContainer}> 
        /* Your component content */
    </div>);
};
Answer
Avatar
Cuban CrocodileOP
@Rain infotech @Ray
Thanks it worked my problems was just i had done no-repeat in background-image so thats why image was not loading
like this,,,,,
.backgroundContainer {
background-image: url("/your-background-image.jpg") no-repeat;
}