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)
小智 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)
由于某些原因,我无法解释接受的答案对我不起作用。(我想用一张图片作为全身的封面图片)。
但是,这里有一个对我有用的替代方法,它可能对遇到的人有用。
在位于静态文件目录中的 css 文件中,我编写了以下内容:
CSS:
body {
background: url(../main/img/picture-name.jpg);
}
Run Code Online (Sandbox Code Playgroud)
您不必包含*'{% load static %}'* 在您的 css 文件中。
HTML:
包括{%load static%}在顶部
创建一个链接 href 样式,如下所示。
<link href='{% static "/main/home.css" %}' rel='stylesheet' type='text/css'>
| 归档时间: |
|
| 查看次数: |
28795 次 |
| 最近记录: |