Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for How to Use TailwindCSS with Flask
Sachin
Sachin

Posted on • Originally published atgeekpython.in

     

How to Use TailwindCSS with Flask

TailwindCSS is a utility-first CSS framework for rapidly creating custom user interfaces. The main advantage of using TailwindCSS is that it is a highly customizable, low-level CSS framework and lets the user take full control of it.

It is a utility-first CSS framework which means that it provides utility classes to build custom designs without writing CSS as we do it traditionally. It puts an end to the use of weird names for CSS classes and IDs.

In this article, we'll learn how to merge the TailwindCSS into our Flask app.

Building a flask app

Installing Flask

Before creating a flask app, we'll begin the installation first. Open up your terminal and run the following command.

pipinstallflask
Enter fullscreen modeExit fullscreen mode

Creating the flask server

Next, we'll lay the pipeline for creating the flask server. Start by creating a folder in which we'll put our files then inside that folder create anapp.py file.

Then, we'll create a subfolder calledtemplates in which we'll store our HTML files and then create another subfolder calledstatic which will be holding styles, scripts, and static images for our frontend.

flask_folder/├──app.py├──static└──templates
Enter fullscreen modeExit fullscreen mode

In ourapp.py file we'll add the following code to create a flask server

fromflaskimportFlask,render_templateapp=Flask(__name__)@app.route("/")defindex():returnrender_template("index.html")if__name__=='__main__':app.run(debug=True)
Enter fullscreen modeExit fullscreen mode

The above code will create a simple flask server with a route that will be responsible for displaying the webpage from theindex.html file which we haven't created yet.

Add a new file calledindex.html inside thetemplates subfolder.

In ourindex.html file add the following HTML

<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>Title</title></head><body><h1>Hi, there!!</h1></body></html>
Enter fullscreen modeExit fullscreen mode

Let's start our server by running the following command in our terminal

python app.py
Enter fullscreen modeExit fullscreen mode

This will start our development server and we can see our webpage serving onhttp://127.0.0.1:5000.

Adding TailwindCSS into flask

We'll now perform the following steps to merge the CSS framework(TailwindCSS) into our flask app.

Installing TailwindCSS

We can use eithernpm oryarn to install the dependency in our project folder. Run the following command in the terminal for installing TailwindCSS usingnpm andyarn respectively.

npminstalltailwindcss
Enter fullscreen modeExit fullscreen mode

OR

yarn add tailwindcss
Enter fullscreen modeExit fullscreen mode

I am using npm for this tutorial.

After running the command, the installation will begin and the following files will be created in the root directory.

flask_folder/├──node_modules/├──package.json└──package-lock.json
Enter fullscreen modeExit fullscreen mode

Creating a configuration file

Run the following command in the terminal to create a configuration file.

npx tailwindcss init
Enter fullscreen modeExit fullscreen mode

The command will create a minimaltailwind.config.js file at the root of the project.

module.exports={content:[],theme:{extend:{},},plugins:[],}
Enter fullscreen modeExit fullscreen mode

We need to do some modifications to thecontent section of thetailwind.config.js to configure the paths to all of your HTML templates.

module.exports={mode:'jit',content:["./templates/**/*.{html,htm}"],theme:{extend:{},},plugins:[],}
Enter fullscreen modeExit fullscreen mode

We just added thetemplates folder where all the HTML files will go and used theglob pattern which makes it easy to match all of the content files in the project.

  • Use* to match anything except slashes and hidden files
  • Use** to match zero or more directories
  • Use comma separate values between {} to match against a list of options

Additionally, we enabled thejit (just-in-time) mode since the JIT mode generates the CSS on-demand by scanning the template files.

Creating CSS files and adding tailwind directives

Inside thestatic folder, create two CSS folders namedsrc andcss and inside these folders addinput.css andmain.css files respectively.

flask_folder/└──static/├──css/└──main.css└──src/└──input.css
Enter fullscreen modeExit fullscreen mode

Now, add the following code inside thesrc/input.css file to insert Tailwind’s base, components, and utilities styles into the CSS.

src/input.css file

@tailwindbase;@tailwindcomponents;@tailwindutilities;
Enter fullscreen modeExit fullscreen mode

Starting the build process

To generate the CSS from the preprocessor directives, we need to run the following command in the terminal.

npx tailwindcss-i ./static/src/input.css-o ./static/css/main.css--watch
Enter fullscreen modeExit fullscreen mode

Note: We will have to run the above code every time we add CSS to our HTML files to see the changes. So the best practice would be to make the above command a script, that will rebuild the CSS without the need to run the CSS build process code every time.

In thepackage.json file add thescripts

{"dependencies":{"tailwindcss":"^3.1.8"},"scripts":{"create-css":"npx tailwindcss -i ./static/src/input.css -o ./static/css/main.css --watch"}}
Enter fullscreen modeExit fullscreen mode

Now, run the scriptcreate-css in the terminal

npm run create-css
Enter fullscreen modeExit fullscreen mode

The above command will eliminate the need to run the CSS build process every time after changing the code inside the HTML file.

Creating frontend with TailwindCSS

Now, to test if it is working, use the utility classes of the TailwindCSS to style the templates. Head over to thetemplates/index.html and edit the file.

Link thecss/main.css file in the Head tag inside theindex.html.

<linkhref="{{url_for('static',filename='css/main.css')}}"rel="stylesheet">
Enter fullscreen modeExit fullscreen mode

templates/index.html

<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metacontent="width=device-width, initial-scale=1.0"name="viewport"><title>Merge TailwindCSS into Flask app</title><linkhref="{{url_for('static',filename='css/main.css')}}"rel="stylesheet"></head><body><sectionclass="text-gray-600 body-font"><divclass="container px-5 py-24 mx-auto"><h1class="text-3xl font-medium title-font text-gray-900 mb-12 text-center">Testimonials</h1><divclass="flex flex-wrap -m-4"><divclass="p-4 md:w-1/2 w-full"><divclass="h-full bg-gray-100 p-8 rounded"><pclass="leading-relaxed mb-6">Synth chartreuse iPhone lomo cray raw denim brunch everyday carry neutra before they sold out fixie 90's microdosing. Tacos pinterest fanny pack venmo, post-ironic heirloom try-hard pabst authentic iceland.</p><aclass="inline-flex items-center"><imgalt="testimonial"src="https://dummyimage.com/106x106"class="w-12 h-12 rounded-full flex-shrink-0 object-cover object-center"><spanclass="flex-grow flex flex-col pl-4"><spanclass="title-font font-medium text-gray-900">Holden Caulfield</span><spanclass="text-gray-500 text-sm">UI DEVELOPER</span></span></a></div></div><divclass="p-4 md:w-1/2 w-full"><divclass="h-full bg-gray-100 p-8 rounded"><pclass="leading-relaxed mb-6">Synth chartreuse iPhone lomo cray raw denim brunch everyday carry neutra before they sold out fixie 90's microdosing. Tacos pinterest fanny pack venmo, post-ironic heirloom try-hard pabst authentic iceland.</p><aclass="inline-flex items-center"><imgalt="testimonial"src="https://dummyimage.com/107x107"class="w-12 h-12 rounded-full flex-shrink-0 object-cover object-center"><spanclass="flex-grow flex flex-col pl-4"><spanclass="title-font font-medium text-gray-900">Alper Kamu</span><spanclass="text-gray-500 text-sm">DESIGNER</span></span></a></div></div></div></div></section></body></html>
Enter fullscreen modeExit fullscreen mode

Flask app using TailwindCSS

Preview of flask app using tailwind css

Conclusion

Usually, developers prefer to use Bootstrap to build UI for the frontend, but in this tutorial, we integrated TailwindCSS into our flask app.

We've covered the following steps in this tutorial

  • Created a demo flask app.

  • Installed the TailwindCSS into the project root directory and Configured it.

  • Added tailwind directives in the CSS files.

  • Ran the command to generate the CSS from the directives.


That's all for now

Keep Coding✌✌

Top comments(3)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
janmpeterka profile image
Jan Peterka
Mostly creating new things with Ruby on Rails these days.
  • Location
    Prague
  • Work
    BE programmer
  • Joined

hi, thanks! we are currently using Bootstrap, but thinking of migration to Tailwind. But I wonder - is it worth it? What are upsides of Tailwind? Thanks!

CollapseExpand
 
sachingeek profile image
Sachin
A Python developer obsessed with Machine Learning and Data Science.
  • Location
    Delhi
  • Joined

First of all, It will take lot of effort migrating from Bootstrap to TailwindCSS if your codebase is huge. It's fine to use Bootstrap in that case. But TailwindCSS gives you more flexibility and customizations.

CollapseExpand
 
sophyia profile image
Sophia Iroegbu
Developer Advocate | Software Engineer

this is a really good guide, thanks for sharing

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

A Python developer obsessed with Machine Learning and Data Science.
  • Location
    Delhi
  • Joined

More fromSachin

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp