【问题标题】:How to add images in CSS file? I am using python flask for website development如何在 CSS 文件中添加图像?我正在使用 python 烧瓶进行网站开发
【发布时间】:2019-09-19 19:06:12
【问题描述】:

在 Python Flask 之前一切正常。现在我尝试将我的 HTML 页面与 Python Flask 连接起来。 CSS 工作正常,但是当我在 CSS 文件中定义图像时,图像不再加载到网站中。相反,它显示错误 404。

python app.py 代码

from flask import Flask, render_template, url_for

app = Flask(__name__ , static_url_path='/static')

@app.route('/')
def index():
    return render_template('/intro.html')

if __name__ == '__main__':
    app.run(debug=True)

HTML 代码:-

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width-device-width, initial-scale=1.0">

        <title>NewliFit</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
        <link rel="stylesheet" href="{{ url_for('static',filename='css/owl.carousel.css') }}">
        <link rel="stylesheet" href="{{ url_for('static',filename='css/owl.carousel.min.css') }}">
        <link rel="stylesheet" href="{{ url_for('static', filename = 'css/owl.theme.default.css') }}">
        <link rel="stylesheet" href="{{ url_for('static',filename='css/firstone.css') }}">
    </head>
    <body>
        <div class="main">
            <div class="cover-image">
                <div class="menu">
                    <div class="leftmenu">

CSS 文件

@charset "utf-8";
/* CSS Document */

*{
    margin: 0px ;
    padding: 0px ;
}
/* ------------cover image -------------*/
.cover-image {
    background-image: url({{ url_for('static',filename = '/images/cover4.jpg')}});
    background-size: 100% 100%;
    width: 100%;
    height: 110vh;
}

请帮忙。

【问题讨论】:

  • 首先你需要static_url_path='/static',而这是默认的静态文件夹。其次更改为background: url("/static/images/cover.jpg") 我希望你的静态文件夹在你的项目根文件夹和里面的css文件夹下。

标签: python html css image flask


【解决方案1】:

您在 CSS 文件中使用 url_for,这不起作用。您需要在 HTML 文件中指定背景图片的 url,或者在 CSS 中指定正确的 URL。

所以要么把它添加到你的 CSS 中:

background-image: url('/static/images/cover4.jpg')}});

或者将 HTML 文件中的封面图像 div 更改为:

<div class="cover-image" style="background-image: url({{ url_for('static',filename = '/images/cover4.jpg')}});">

除非您打算定期更改静态文件夹(或封面图片),否则我建议您采用第一条路线,以确保您将样式和语义分开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-29
    • 2012-08-03
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 2021-03-28
    相关资源
    最近更新 更多