Using Bootstrap with Flask
Key Concepts
- Integrating Bootstrap with Flask
- Using Bootstrap Components
- Customizing Bootstrap Styles
Integrating Bootstrap with Flask
Bootstrap is a popular CSS framework that provides pre-designed components and styles to help build responsive and mobile-first websites. To use Bootstrap with Flask, you need to include Bootstrap's CSS and JavaScript files in your Flask application.
You can include Bootstrap by linking to its CDN in your HTML templates. Here's how you can do it:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
This will make Bootstrap's styles and scripts available in your Flask application.
Using Bootstrap Components
Bootstrap provides a variety of pre-designed components like navigation bars, buttons, forms, and modals. These components can be easily integrated into your Flask templates.
For example, to create a navigation bar using Bootstrap, you can use the following HTML:
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Flask Training</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </nav>
This code snippet creates a responsive navigation bar that collapses into a toggleable menu on smaller screens.
Customizing Bootstrap Styles
While Bootstrap provides a lot of pre-designed styles, you might want to customize them to match your application's branding. You can override Bootstrap's default styles by adding your custom CSS.
First, create a custom CSS file in your Flask application's static directory, for example, static/custom.css
. Then, link this custom CSS file in your HTML templates after the Bootstrap CSS:
<link href="{{ url_for('static', filename='custom.css') }}" rel="stylesheet">
In your custom CSS file, you can override Bootstrap's styles. For example, to change the color of all buttons to green, you can add the following CSS:
.btn-primary { background-color: green; border-color: green; }
This will change the background color of all primary buttons to green, while keeping the rest of Bootstrap's styles intact.