Parth Patel
Parth Patel

Reputation: 155

CSS Background Images with Flask

I have read other questions about getting background images in flask to show, but none of the suggested solutions worked for me and I get a 404 error(127.0.0.1 - - [22/Feb/2018 15:13:33] "GET /img/showcase.jpeg HTTP/1.1" 404 -). The jpeg image I want to set as the background is located in the static folder and called showcase.jpeg. Here is my code. Any suggestions? Here's the HTML Link to my style.css:

<link rel="stylesheet" type="text/css" href="{{url_for('static',filename='style.css')}}">

CSS FILE:

#showcase{
  background-image: url({{ url_for ('static', filename = 'showcase.jpeg') }});
  height: 100vh;
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding: 0 20px;
  font-weight: bold;
}

Folders

Upvotes: 4

Views: 20142

Answers (4)

Frish
Frish

Reputation: 1421

CSS files are read as static files, so you shouldn't be using the url_for method in your CSS.

If your file structure is:

static
  -img
  -css

Use background-image: url(../img/showcase.jpeg)

Relevant SO

Upvotes: 11

Nikita
Nikita

Reputation: 11

Do:

background-image: url('../images/pic.png');

where static->images->pic.png.

Upvotes: 1

Sailer
Sailer

Reputation: 11

Do:

background-image: url('/static/showcase.jpeg');

It worked for me.

Upvotes: 1

MeloGuo
MeloGuo

Reputation: 61

This is my directory tree structure: directory tree structure

And you could write background-image like this:

background-image: url(../img/nodejsEventLoop.png);

Upvotes: 6

Related Questions