How to use Flask url_for in a CSS file?

You can't use Jinja directly in the CSS file since you normally don't render it as a template, but there is 3 alternate way to achieve your need:

Method 1

Use correct relative path in your CSS file:

background: url("/static/images/bg.jpg") no-repeat 0px 0px;

Method 2

Put your background line into the template:

<style>
    background: url("{{ url_for('static',filename='images/bg.jpg') }}") no-repeat 0px 0px;
</style>

Method 3

Define a CSS variable in your template:

<style>
    :root {
        --background-url: {{ url_for('static', filename='images/bg.jpg') }}
    }
</style>

Then use it in your CSS file:

background: url("var(--background-url)") no-repeat 0px 0px;

You are serving css statically, via /static/css/style.css. When you do this, then Flask does not use Jinja to parse the CSS file as though it were a template.

If, however, you had a route (eg @app.route('/css/<file>')) then you could use the render_template() method to render your CSS file as though it were a jinja template, which would then parse the jinja directives (such as {{url_for()}})