【问题标题】:django css background-image url not workingdjango css 背景图像 url 不起作用
【发布时间】:2020-06-20 05:29:58
【问题描述】:

所以我有这个标题任务类,但由于某种原因,背景图像不会显示,但是当我在 Visual Studio 代码中单击 url 时,它会显示来自 url 的图像。有人知道我的代码有什么问题吗?谢谢

 .header-task{
  background-image: url("..\image\nightlandscape.jpg");
  background-repeat: no-repeat;
  background-size: 100% 200%;
  height: 120px;
  position: relative;
}

这是我单击 URL 图片时的 Visual Studio 代码图片

【问题讨论】:

  • 你的文件夹结构是什么?我相信您的图像路径不正确。看看这里:docs.djangoproject.com/en/3.0/howto/static-files
  • 我编辑我的问题,以便您查看我的文件夹结构
  • assets 是我的 static_root 文件夹
  • 请参阅此帖子以获取解决方案stackoverflow.com/questions/62471742/…
  • 我不认为静态是问题,因为我在我的 html 中加载了静态并且它工作得很好,也许我的 css 上的 url 是问题

标签: css django


【解决方案1】:

我做了一些挖掘,但我个人没有测试它的环境。所以你可能需要自己检查一下。

你可以试试下面的:

 .header-task{
  background-image: url("static(image/nightlandscape.jpg"));
  background-repeat: no-repeat;
  background-size: 100% 200%;
  height: 120px;
  position: relative;
}

如果您的 STATIC_URL 是 '/static/'(我相信在 settings.py 中),这将呈现为:

 .header-task{
  background-image: url("/static/image/nightlandscape.jpg");
  background-repeat: no-repeat;
  background-size: 100% 200%;
  height: 120px;
  position: relative;
}

另一种可能性:

 .header-task{
  background-image: url('{% static 'nightlandscape.jpg' %}') or url('{% static "/img/nightlandscape.jpg" %}')
  background-repeat: no-repeat;
  background-size: 100% 200%;
  height: 120px;
  position: relative;
}

但为此,我认为您需要先加载静态文件:{% load static%} 在您的 HTML 中,然后加载样式表。

<head>
    <style>
        {% include "path/to/my_styles.css" %}
    </style>
</head>

可能只是将url("..\image\nightlandscape.jpg") 更改为url("../image/nightlandscape.jpg")

【讨论】:

  • 背景图片:url("/static/image/nightlandscape.jpg");只有这个对我有用。
【解决方案2】:

我确实有一个类似的用例,我在 CSS 文件中调用背景图像如下

.class-name{
  background-image: url('../img/img.png');
}

我有一个对应的文件夹结构:

Static
   Css
      file.css
   Img
      img.png

可能是它无法解析的文件夹结构。

【讨论】:

    【解决方案3】:

    它对我有用:

    background-image: url( '/static/images/moon.jpg');
    

    编码愉快。

    【讨论】: