在 Django 中,要在 CSS 文件中添加背景图片,您可以遵循以下步骤:
static
的文件夹中(如果尚未创建该文件夹,请创建一个)。background-image
属性定义背景图片。假设您的图片名为 my_background.jpg
,并位于 static/images
文件夹中,您的 CSS 类可以如下所示:.my-background {
background-image: url('../static/images/my_background.jpg');
background-size: cover; /* this will cover the entire element */
background-repeat: no-repeat; /* this will prevent the image from repeating */
}
<head>
标签内,例如:{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'css/my-stylesheet.css' %}">
<title>My Django App</title>
</head>
<body>
<div class="my-background">
<!-- Your content here -->
</div>
</body>
</html>
注意 {% load static %}
模板标签,它允许您在模板中使用静态文件。
现在,当您加载页面时,应该看到指定的背景图片已应用于具有 my-background
类的元素。
领取专属 10元无门槛券
手把手带您无忧上云