3

I'm creating a website(creating using React). so I want to add a full-screen image for the Home page. I'm using CSS module. when importing an image into the module.css it's not rendered. How can I fix this. Here is my code. I'm importing this (scr => assets folder)

codesandbox-link

Home.js

import React from 'react'
import styles from '../styles/Home.module.css'
 
const Home = () => {
    
    return (
        <div className={styles.Hero} ></div>       
                             
        
    )
}

export default Home

Home.module.css

.Hero {
  background-image: url(../assets/hero.jpg);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
avishka
  • 171
  • 1
  • 5
  • 19
  • 1
    Hello @AjeetShah here is codesandbox link https://codesandbox.io/s/stupefied-burnell-ndkzj?file=/src/App.module.css – avishka Mar 17 '21 at 04:12
  • Look at the code in the browser, what's the class name of the div? Should it be `Hero`, instead? – Adriano Mar 17 '21 at 04:32
  • I request you to go through this question to get better insight https://stackoverflow.com/questions/39195687/setting-a-backgroundimage-with-react-inline-styles – saurav Mar 17 '21 at 05:10

3 Answers3

2

It is CSS issue, your div, which is supposed to show the image in the background, has no height and width:

Background image is loading perfectly after adding below styles:

Global CSS (styles.css):

html,
body,
#root {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

App.module.css:

.Hero {
  background-image: url(./assets/hero.jpg);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
  width: 100%;
}

and in App.js:

import styles from "./App.module.css";

export default function App() {
  return (
    <div style={{ width: "100%", height: "100%" }}>
      <div className={styles.Hero}></div>
    </div>
  );
}

I am not good at CSS. So, this may not be the perfect way to handle stylings (height / width). So, you may improve it. Here is the full code*.


As mentioned in docs, with webpack, you can load images in CSS as:

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

Webpack finds all relative module references in CSS (they start with ./) and replaces them with the final paths from the compiled bundle.

*I provided full code as the image was not showing in codesandbox, but showing at my local machine.

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
1

Try this in a non-sandbox environment. The way you have imported className is fine. I have a feeling sandbox is not reflecting it properly. You can also try -

content:url(<path to image>);

in the className instead of background-image:url

0

I used the background in color and succeeded but the image didn't, you can import the image into App.js

 import image from "./url";

 return (
  <img src={image} alt="" />
 )
 
Bon Pham
  • 23
  • 4