在Django的css文件中使用background-image的方法

yam*_*han 18 css django background-image

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

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

但这不起作用.

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

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

也不行.

当你在css文件上使用background-image时,你通常如何编写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" %}" />
Run Code Online (Sandbox Code Playgroud)

Django版本:1.9.2

Pra*_*edi 30

用这个:

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

最有可能这将工作.在您的图像URL之前使用"/ static /"然后尝试它们.谢谢


小智 9

background-image: url('{% static '.jpg' %}');
Run Code Online (Sandbox Code Playgroud)

  • 虽然此代码可以提供问题的解决方案,但最好添加有关其工作原理/原因的上下文。这可以帮助未来的用户学习并将这些知识应用到他们自己的代码中。当代码被解释时,您也可能会以点赞的形式得到用户的积极反馈。 (2认同)

小智 8

确保它django.contrib.staticfiles包含在您的 INSTALLED_APPS 中。

在 settings.py 文件中定义 STATIC_URL: STATIC_URL = '/static/'

     {% load static %}
     <img src="{% static "my_app/example.jpg" %}" alt="My image"/>
Run Code Online (Sandbox Code Playgroud)

或者

     #third{
          background: url('{{ STATIC_URL }}my_app/example.jpg'
     }
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的建议,LuKs Sys。我可以问你一个问题吗?我什至可以在“site.css”中写入“{{ STSTIC_URL }}”吗?我是否需要在没有“{% load static %}”或其他内容的情况下编写此内容?或者你最后的代码应该写在html文件中? (3认同)

Sim*_*mas 7

由于某些原因,我无法解释接受的答案对我不起作用。(我想用一张图片作为全身的封面图片)。

但是,这里有一个对我有用的替代方法,它可能对遇到的人有用。


在位于静态文件目录中的 css 文件中,我编写了以下内容:

CSS:

body {
  background: url(../main/img/picture-name.jpg); 
}
Run Code Online (Sandbox Code Playgroud)

您不必包含*'{% load static %}'* 在您的 css 文件中。

HTML:

  1. 包括{%load static%}在顶部

  2. 创建一个链接 href 样式,如下所示。

    <link href='{% static "/main/home.css" %}' rel='stylesheet' type='text/css'>