kdam
kdam

Reputation: 191

How to import images into CSS Modules?

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

Upvotes: 3

Views: 5896

Answers (3)

Ajeet Shah
Ajeet Shah

Reputation: 19863

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.

Upvotes: 3

Anuraag Gupta
Anuraag Gupta

Reputation: 11

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

Upvotes: 1

Bon Pham
Bon Pham

Reputation: 23

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

Upvotes: 0

Related Questions