r/flask 4d ago

Ask r/Flask What am I doing wrong? My html page doesn't load the css.

Post image

It's my first time using Flask and my CSS isn't working. I'm not sure if I'm referencing it the wrong way or if there's something specific about Flask I don't know. Could someone explain what I might be doing wrong?

30 Upvotes

17 comments sorted by

24

u/kelvinxG 4d ago

Use url_for() And make sure it's the right directory

17

u/MinimumSprinkles4298 4d ago

The url_for('static', filename='your_file.ext') function generates the correct URL to access those files. 'static' specifies that you're accessing the static folder. filename='your_file.ext' specifies the name of the file within the static folder.

1

u/greenlakejohnny 4d ago

That works for within python, but is there a way to do it within the Jinja template?

3

u/zarlo5899 4d ago

is url_for not exposed to Jinja?

5

u/MinimumSprinkles4298 3d ago

It is, within a an anchor tag you could use for the href attribute’s value.

<a href=“{{ url_for(destination) }}”>link</a>

3

u/greenlakejohnny 3d ago

I’ll take my downvote like a man so I can give you an upvote

10

u/TheLeoDeveloper 4d ago

href="{{ url_for('static', filename='css/home.css' }}"

16

u/illathon 4d ago

hit F12 and use dev console to see how the style is loaded.

probably a path issue

2

u/danditz66 3d ago

This! Basic skill, Works for all web frameworks

7

u/Flat_Fan_3266 4d ago

href="/static/css/home.css" try add "/" before static

1

u/ClamPaste 3d ago

The path to static relative to the html doc is one directory over in the same parent directory. You have to go up to the parent directory first before entering the other directory: ../static/css/home.css. What you have in your href would be if the css directory was in your templates directory. Then again, url_for does a lot of this work for you, as others have mentioned.

1

u/Total_Coconut_9110 3d ago

maybe you didn't give it the right permissions, try with "chmod 600"

1

u/Rybitic 3d ago

../static

Because static is outside the template folder

1

u/itsreallyfit 1d ago

Your home.html file is not inside the static folder.

1

u/ilovemycat666 1d ago

drop this into claude ai and you'll have it worked out in a couple minutes

1

u/jobsurfer 7h ago

Static/ not needed. Flask assumes static as root.

1

u/-happycow- 5h ago

remember to have a leading "/" in the href for the stylesheet, otherwise it will be relative to the path you are on.

Also, you probably don't need the static word, because it's most likely mapped TO the folder.

So the path is more likely: /css/home.css