4

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;
}
3

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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="" />
 )
 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.