Django 在 css 文件中使用背景图像的方法

新手上路,请多包涵

我想在 Django 上使用图像文件作为背景图像。但是我不知道怎么做。首先,我阅读 了这篇 文章并尝试在 css 文件中像下面这样写。

 #third{
    background: url("img/sample.jpeg") 50% 0 no-repeat fixed;
    color: white;
    height: 650px;
    padding: 100px 0 0 0;
}

但这不起作用。

 {% load staticfiles %}
#third{
    background: url({% static "img/sample.jpeg" %}) 50% 0 no-repeat fixed;
}

#third{
    background: url("../img/sample.jpeg") 50% 0 no-repeat fixed;
}

也不行。

当您在 css 文件上使用背景图像时,您通常如何编写 css 文件?你能给我一些建议吗?

 C:\~~~~~~> dir hello\static\img
2016/09/28  19:56             2,123 logo.png
2016/09/24  14:53           104,825 sample.jpeg

C:\~~~~~~> dir hello\static\css
2016/09/29  20:27             1,577 site.css

C:\~~~~~~> more lemon\settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static'),
)

C:\~~~~~~> more hello\templates\base.html
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "css/site.css" %}" />

Django 版本:1.9.2

原文由 yamachan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

用这个:

     #third{
     background: url("/static/img/sample.jpeg") 50% 0 no-repeat fixed;
     color: white;
     height: 650px;
     padding: 100px 0 0 0;
     }

很可能这会起作用。在您的图像 URL 之前使用“/static/”,然后尝试它们。谢谢

原文由 Prakhar Trivedi 发布,翻译遵循 CC BY-SA 3.0 许可协议

background-image: url('{% static '.jpg' %}');

原文由 Abdullah Tahir 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题