How to add CSS and Other files used in your Webpage

How to add CSS and Other files used in your Webpage

One of the most important things in web development is the website's interface and its looks. So it is just simple when comes to linking your stylesheet or media source for your webpage. But in FLASK, it isn't that easy or difficult. Since Flask is not often used for web development doesn't have so much versatility.

So like in the previous article, we have html templates stored in the templates Folder. So the flask fetches resources in an organized manner. That's the reason we need to store the resources in respective folders

So to use the StyleSheet and other media resources you must first create a folder named static in which you can store resource folders and files in your way. Below is the file structure of the flask app.

As you can see all the files are not in the root folder but stored in their respective folders. The python files are always stored in the root folder.

The file paths used in the code are all about the file structure mentioned above.

Let's see how to add the links for stylesheets, Js files and Media

StyleSheet

<link href="{{url_for('static', filename='style.css')}}">

Here the file path is specified as if the file is in the static folder so no need of adding ../static/style.css No need of adding that kind of path. The static represents the static folder. and again it's all for the flask to understand.

No will see how to link the stylesheet present in the subfolders

Assume that our stylesheet is in the CSS folder where we got different stylesheets or maybe we want our files organized or maybe you are using any CSS preprocessor.

<link href="{{url_for('static', filename='Css/style.css')}}">

your need to just specify the path after the static folder. You can link multiple stylesheets to one HTML document with no restrictions from Flask. Same applies to the Javascript files.

Javascript

<script src="{{url_for('static', filename='main.js')}}">

Images / Media files

<img src="{{url_for('static', filename='imagename.jpg')}}">

It's the same for the media files also. Try this out

⚠ Storing these kinds of files in folders other than static will lead to problem flask won't recognize it. Those can be stored in different folders which are in Static folder but not in any other folder

Meet you in the next blog post