[英]Setting background image to a div in nextjs not working
I am new to nextjs and I dont understand why the background image is not being set for this div.我是 nextjs 的新手,我不明白为什么没有为这个 div 设置背景图像。 In the root dir I have a folder called public, which I have the art-thing.jpg
file in. styles.css
is in the root dir.在根目录中,我有一个名为 public 的文件夹,其中包含art-thing.jpg
文件styles.css
在根目录中。 index.js
is in the pages dir in the root dir. index.js
位于根目录的 pages 目录中。 I can set the background to a color but I can not set it to a image.我可以将背景设置为颜色,但不能将其设置为图像。 There is a post of someone with a similar problem but I would like my css to not be inline.有人有类似问题的帖子,但我希望我的 css 不是内联的。
styles.css styles.css
html {
scroll-behavior: smooth;
height: 100%;
}
body {
margin: 0px;
padding: 0px;
}
.page-container {
height: 100vh;
position: relative;
}
.page-container-welcome {
height: 100vh;
position: relative;
background-size: cover;
background-image: url("/public/img/Branding/art-thing.jpg");
}
.content-wrap{
padding-bottom: 2.5rem;
}
index.js index.js
import 'bootstrap/dist/css/bootstrap.min.css';
import Head from 'next/head';
import HekateNav from "../client/components/nav";
import Footer from "../client/components/footer";
function Home() {
return (
<div>
<Head>
<title>Hekate</title>
</Head>
<div className="page-container-welcome">
<div className="content-wrap">
<HekateNav/>
</div>
</div>
<Footer/>
</div>
);
};
export default Home
console error that I get我得到的控制台错误
DevTools failed to load SourceMap: Could not load content for http://localhost:3000/_next/static/css/bootstrap.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
The solution was to change the path of the image by removing the public path.解决方案是通过删除公共路径来更改图像的路径。 It was answered here .它在这里得到了回答。 Change path to /img instead of /public/image.将路径更改为 /img 而不是 /public/image。 /public is the actual root of the site in this case. /public 在这种情况下是站点的实际根目录。
.page-container-welcome {
height: 100vh;
position: relative;
background-size: cover;
background-image: url("/img/art-thing.jpg");
}
try this.尝试这个。
step1.步骤1。
follow this link to install "next-images" https://github.com/twopluszero/next-images按照此链接安装“下一个图像” https://github.com/twopluszero/next-images
//next.config.js
const withImages = require("next-images");
module.exports = withImages();
step2.第2步。
import your target image and use it into custom styles like this code.导入您的目标图像并将其使用到自定义 styles 中,就像此代码一样。
//index.js
import artImage from '/image/Branding/art-thing.jpg'
//don't use public folder to use static image, make 'image' folder in root path
const useStyles = makeStyles(()=>{
pageContainerWelcome: {
height: '100vh',
background: 'url(' + artImage + ')',
...
...
},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.