首页 > 解决方案 > 我在我的 react js 中添加了背景图片。但它显示一个错误

问题描述

我在互联网上看到他们告诉要在公用文件夹中添加图像。所以我通过创建一个子文件夹名称 img 将我的图像添加到公共文件夹中,我将我的图像“mario.png”放入其中。

因为我想将该图像添加为背景图像,所以我在 index.css 中编写了这段代码


body{
    margin:0;
    padding: 0;
    font-family: sans-serif;
    background: url(/img/mario.png);
    background-size: 100%;
    background-position: bottom;
    background-color: #95e8f3;  
    min-height: 100%;
}

但它仍然没有工作它显示错误:** ./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./ node_modules/postcss-loader/src??postcss!./src/index.css) 错误:无法解析 'D:\Users\PIRATES\Desktop\cool\src' 中的 '/img/mario.png' **

这是文件夹结构

但是当我在 src 中创建一个资产文件夹时,它正在工作,但我想知道为什么当我将图像放在公用文件夹中时它不工作。

标签: cssreactjs

解决方案


您没有url正确使用功能。文档

body{
    margin:0;
    padding: 0;
    font-family: sans-serif;
    background: url("/img/mario.png");
    background-size: 100%;
    background-position: bottom;
    background-color: #95e8f3;  
    min-height: 100%;
}

推荐阅读