【问题标题】:Setting background image to a div in nextjs not working在 nextjs 中将背景图像设置为 div 不起作用
【发布时间】:2020-09-12 11:46:25
【问题描述】:

我是 nextjs 的新手,我不明白为什么没有为这个 div 设置背景图像。在根目录中,我有一个名为 public 的文件夹,其中包含 art-thing.jpg 文件。styles.css 在根目录中。 index.js 位于根目录的 pages 目录中。我可以将背景设置为颜色,但不能将其设置为图像。有人有类似问题的帖子,但我希望我的 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


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

我得到的控制台错误

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

【问题讨论】:

    标签: html css jsx next.js


    【解决方案1】:

    解决方案是通过删除公共路径来更改图像的路径。已回答here将路径更改为 /img 而不是 /public/image。在这种情况下,/public 是网站的实际根目录。

    .page-container-welcome {
        height: 100vh;
        position: relative;
        background-size: cover;
        background-image: url("/img/art-thing.jpg");
    }
    

    【讨论】:

      【解决方案2】:

      试试这个。

      第一步。

      点击此链接安装“next-images” https://github.com/twopluszero/next-images

      //next.config.js
      
      const withImages = require("next-images");
      module.exports = withImages();
      

      第二步。

      导入您的目标图像并将其用于自定义样式,如此代码。

      //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 + ')',
            ...
            ...
         },
      }
      

      【讨论】:

        猜你喜欢
        • 2017-01-11
        • 1970-01-01
        • 2022-10-07
        • 2012-04-29
        • 1970-01-01
        • 2021-05-15
        • 2017-12-20
        • 2016-06-21
        • 2021-12-27
        相关资源
        最近更新 更多