如何在 Django 模板中设置背景图像?

Posted

技术标签:

【中文标题】如何在 Django 模板中设置背景图像?【英文标题】:How can one set a background image in a Django Template? 【发布时间】:2013-07-08 22:11:20 【问题描述】:

假设我的背景图片的网址是 www.randomlink.com/static/backgroundimagesplash.jpg

我查看了Pinterest 主页。众所周知,Pinterest 是使用 Django 构建的。我在他们的主页上检查了他们的一些元素。

他们使用的其中一个图形是这里的初始图像:PinterestSplashImage.jpg

初始图像设置在底部中心。我注意到的一件事是,初始图像的大小相对于浏览器的大小进行了调整。

这是我当前的主页模板:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<link href="www.randomlink.com/static/favicon.ico" rel="icon" type="image/x-icon">
<head>
<title>Homepage</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style>
body
    font-family:Arial,Helvetica,sans-serif;
    font-size: 12px;

</style>
</head>
<body>
     state 
    <form action="/login/" method="post">
        % if next %
        <input type="hidden" name="next" value=" next " />
        % endif %
        username:
        <input type="text" name="username" value=" username" /><br />
        password:
        <input type="password" name="password" value="" /><br />

        <input type="submit" value="Log In" />
    </form>
</body>
</html>

如何将 www.randomlink.com/static/backgroundimagesplash.jpg 设置在底部中心并使其可调整大小,就像 Pinterest 对其主页所做的那样? (为了争论,初始图像将与 Pinterest 初始图像的尺寸相同)

【问题讨论】:

Django 模板是 HTML。所以你应该问如何在 HTML 页面中设置背景。您可以将背景图像设置为 html 或 body 标签。通常你在 base.html 文件中设置主要的视觉元素。 【参考方案1】:

看看我是怎么做到的:在模板中我放了以下行:

<body id="bg" style="background-image: url('% static "images/33.jpg"%')";>

在css中:

#bg
    background-size: 1800px 900px;
    background-repeat: no-repeat;
    background-position: top;
    background-attachment: fixed;

结果我得到了一个固定的背景和屏幕的比例。

【讨论】:

【参考方案2】:

这个问题与 Django 无关。它是带有 CSS 的纯 html。

要在调整窗口大小时缩放图像,您应该使用 CSS3 的属性background-size: contain

要放置到底部和居中,您可以使用 CSS 的属性 position: absolute; background-position: 50% 100%;

最后一个例子:

<style type="text/css">
.splash 
    bottom: 0;
    left: 0;
    right: 0;
    background-image: url('https://s-passets-ec.pinimg.com/webapp/app/desktop/images/logged_out_splash.77aa6339.jpg?1373235165');
    background-size: contain;
    background-position: 50% 100%;
    background-repeat: no-repeat;
    bottom: 0;
    height: 100%;
    margin: auto;
    max-height: 461px;
    max-width: 1034px;
    position: absolute;
    width: 100%;

</style>

<div class="splash"></div>

在jsfiddle上查看演示

【讨论】:

【参考方案3】:

试试这个在你的模板中设置背景图片:

 <div class="inner" style="background-image: url(% static "frontend/img/parallax-image.jpg" %");>

【讨论】:

以上是关于如何在 Django 模板中设置背景图像?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Django 模板中的“带有模板标签”中设置 Django 渲染块值?

如何在 django 模板中设置自定义 forloop 起点

如何在 django 模板中设置页面范围的索引

如何在颤动中设置背景图像?

如何在 QWebEngineView 中设置背景图像 [重复]

如何使用外部 css 在 Reactjs 中设置背景图像?