My CSS is not linking with HTML

I think the code is right too… External stylesheet not linking on replit I’m a new user
https://replit.com/@AlfiyaAnware/lung-cancer?v=1

Home
<link rel="stylesheet" href="/resources/mystyle.css"  type="text/css" />

Welcome to the community, @AlfiyaAnware!

You will need to change the <link> tag to:

<link rel=“stylesheet” href="{{ url_for('resources', filename='mystyle.css') }}" type=“text/css” />
1 Like

im getting an error

BuildError

werkzeug.routing.exceptions.BuildError: Could not build url for endpoint ‘resources’ with values [‘filename’]. Did you mean ‘renders’ instead?

Am I supposed to do something else as well?

Sorry for not mentioning this:

Since CSS is a static file, it should placed be placed inside the static folder with your home.html file.

Then change the href accordingly.

ok, i created a static folder and placed mystyle.css in it but since I’m using flask I have kept the html file in the templates folder. I’m not getting an error but the CSS attributes still havent been applied.

Also thank you so much for replying I really really appreciate the help as a beginner.

<link rel= "stylesheet" type= "text/css" href= "../static/mystyle.css"

I figured out I had to use this.
Thank you so much for your help

1 Like

Check out this SO post:

TL;DR place {{ url_for('static', filename='mystyle.css') }} instead of mystyle.css
EDIT: Make sure your placing this inside of the href property.

Here's why

Your flask project uses something called Jinja Templates. Jinja Templates are basically HTML with extra features. Since you can’t access code that’s on the server without telling the server to do so, you must place a special piece of text that tells the templating system to return the CSS file.

I did that as well and it worked. I’m wondering how come it doesn’t work when we use another folder path rather than static ?! Because I would like to put all my .css and .js files separate

Flask has a specific way of handling static files like CSS, JavaScript, and images, which is by placing them in a directory named “static” at the root level of your project.

This is part of the Flask design philosophy and it follows the convention over configuration principle. And one of these conventions is placing static files in the “static” folder.

But…

If you wish to organize your static files into different directories, you can still do that within the static directory. For example, you can have a “css” directory and a “js” directory within the “static” directory. For example:

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/mystyle.css') }}">
<script src="{{ url_for('static', filename='js/myScript.js') }}"></script>

This way, you’re still using the static directory that Flask is set up to serve, but you’re also able to organize your static files in a way that makes sense for you

3 Likes