从外部css(Django)加载背景图像时出现问题

2024-09-25 00:22:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Django上通过外部CSS加载图像时遇到问题。它可以很好地使用内联CSS,但我想了解为什么它不能使用外部CSS。如有任何帮助,将不胜感激:

我的树:

├───migrations
│   └───__pycache__
├───static
│   └───website
│       ├───css
│       ├───img
│       └───js
├───templates
│   └───website
└───__pycache__

CSS:

.body {
  background: url('/static/website/img/Racoon.jpg');
}

HTML:

{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="{% static 'website/css/main.css' %}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Russo+One&display=swap" rel="stylesheet">
{% block title %}
<title> Home </title>
{% endblock %}
{% block content %}
<h1> Home </h1>
<p> Homepage of the website </p>
{% endblock %}

settings.py:

STATIC_URL = '/static/'

另外,我使用的是localhost,图像确实是通过URL加载的:http://127.0.0.1:8000/static/website/img/Racoon.jpg


Tags: https图像comimgtitlelinkstaticwebsite
1条回答
网友
1楼 · 发布于 2024-09-25 00:22:57

替换:

.body {
  background: url('/static/website/img/Racoon.jpg');
}

.body {
  background: url('../img/Racoon.jpg');
}

../表示父目录。首先返回static/website文件夹,然后转到img文件夹并找到您的图像

如果仍不工作,请清除浏览器历史记录,然后重试。

相关问题 更多 >