2016-09-29 24 views
5

我想在Django上使用圖像文件作爲背景圖像。但是我不知道怎麼做。 首先,我讀了this,並試圖在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文件上使用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" %}" /> 

Django的版本:1.9.2

+1

[如何引用在我的css文件靜態文件?(HTTP的可能重複://計算器.com/questions/5898776/how-to-refer-to-static-files-in-my-css-files) –

+1

您可以使用相對路徑來指定CSS文件所在的位置(使用'../'上升)或域根的相對路徑(以'/'開始)或絕對路徑(包括域名)。 –

+0

@ timo.rieber感謝您的評論。我在這個網站上閱讀了幾個相同的問題,但我解決不了。我讀了你的鏈接並學到了很多東西。謝謝你。 – yamachan

回答

3

使用此:

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

最有可能這將work.Use 「/靜態/」 圖像的URL,然後再嘗試。謝謝

+0

Thaaaaaaaaank你,Prakhar Trivedi。有效!!我很感謝你。 – yamachan

+1

我的快樂。快樂編碼:) –

1

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

在你settings.py文件定義STATIC_URL:STATIC_URL = '/static/'

 {% load static %} 
    <img src="{% static "my_app/example.jpg" %}" alt="My image"/> 

 #third{ 
      background: url('{{ STATIC_URL }}my_app/example.jpg' 
    } 
+0

感謝您的建議,LuKs Sys。我可以問你一個問題嗎?我是否可以在'site.css'中寫入{{STSTIC_URL}}?我是否需要在不使用「{%load static%}」的情況下編寫它?或者你的最後一個代碼應該是用html文件編寫的? – yamachan

+2

我最後的代碼必須寫入CSS文件,我的第一個代碼必須寫入HTML文件。 –

+0

謝謝你的回覆。我知道了。 – yamachan