【问题标题】:How to load background images using CSS in ExpressJS如何在 ExpressJS 中使用 CSS 加载背景图像
【发布时间】:2021-06-09 10:19:28
【问题描述】:

我正在尝试在 ExpressJS 中制作英雄形象。但是,我发现我无法通过 CSS 的 background-image 加载图像。我尝试使用常规的<img> 标签,但它们会导致奇怪的格式和拉伸问题(this 对我不起作用)。我相信 Express 正在限制通过 CSS 访问图像,我该如何解决这个问题?

(顺便说一下,我使用 .hbs 进行渲染)

这是我目前的代码:

#hero {
  /* disable-check-5 */
  background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
    url("/img/main.jpg");

  height: 60%;

  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
}

#hero-text {
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
}

和哈佛商学院

<div id="hero">
  <div id="hero-text">
    <h1>{{hero.title}}</h1>
    <p>{{hero.text}}</p>
    <a href="/bw/sydney">
      <button class="btn btn-outline-success">{{hero.button-txt}}</button>
    </a>
  </div>
</div>

【问题讨论】:

  • 我有 2 个问题? 1)这条路径 /img/main.jpg 是否正确?就像当你尝试使用 img 标签时路径是一样的? 2) 你是否设置了公共目录来提供静态资源,如图像或样式表?
  • @JatinMehrotra 我尝试使用具有相同路径的 IMG 标签(提供图像,存在格式问题)

标签: node.js express handlebars.js express-handlebars


【解决方案1】:

我建议使用来告诉 express 使用一个目录,该目录将为您的静态资产(如 css、图像或 javascript)提供服务。通常在快递世界中它被称为公共目录,因此您可以在公共创建图像文件夹。

结构类似于项目文件夹的根目录 -> src,公共目录

在你的 app.js 中

const publicDirectoryPath = path.join(__dirname,'./public')
app.use(express.static(publicDirectoryPath))

在您的 HTML 文件中

background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
    url("./img/main.jpg");

注意./public is relative to app.js

【讨论】:

    猜你喜欢
    • 2017-05-01
    • 2011-11-03
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多