如何将图像导入 CSS 模块?

问题描述

我正在创建一个网站(使用 React 创建)。所以我想为主页添加一个全屏图像。我正在使用 CSS 模块。将图像导入 module.css 时,它不会呈现。我怎样才能解决这个问题。这是我的代码。我正在导入这个(scr => assets 文件夹)

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

解决方法

在非沙盒环境中试试这个。您导入 className 的方式很好。 我有一种感觉沙箱没有正确反映它。 你也可以试试-

content:url(<path to image>);

在 className 而不是 background-image:url

,

我使用了彩色背景并且成功了但是图片没有,您可以将图片导入App.js

 import image from "./url";

 return (
  <img src={image} alt="" />
 )
 
,

这是 CSS 问题,您的 div 应该在背景中显示图像,但没有 heightwidth

添加以下样式后背景图片加载完美:

全局 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%;
}

并在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>
  );
}

我不擅长 CSS。因此,这可能不是处理样式(高度/宽度)的完美方式。所以,你可以改进它。这是完整的code*。


如文档中的 mentioned 一样,使用 webpack,您可以将 CSS 中的图像加载为:

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

Webpack 在 CSS 中查找所有相关模块引用(它们以 ./ 开头),并用编译包中的最终路径替换它们。

*我提供了完整的代码,因为图像没有显示在代码和框中,而是显示在我的本地机器上。