Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 72 ยท Templates with Jinja

Styling Flask Apps with Bootstrap and Bootstrap-Flask

Style a Flask app with Bootstrap 5. Load it from a CDN or locally, build a responsive base template, and use Bootstrap-Flask macros to render forms, flash messages, navigation and tables.

Writing good-looking CSS from scratch takes time. Bootstrap is a popular CSS framework with ready-made, responsive components: a grid, buttons, forms, cards, navigation bars, alerts, tables and modals. You add its stylesheet to your pages and put its class names on your HTML elements. Because Flask sends whatever HTML your templates produce, Bootstrap works with Flask like with any other site.

This lesson shows two levels. First, plain Bootstrap in a Flask base template. Then Bootstrap-Flask, a small extension that adds Jinja macros which render whole forms, flash messages, nav items, pagination and tables with the right Bootstrap markup, saving you from writing the same boilerplate over and over.

The quickest start is the CDN: two tags in the <head> and before </body>. Bootstrap's own documentation lists the exact tags (with integrity hashes) for the current version; Bootstrap 5.3 is used below. The JavaScript bundle is only needed for interactive parts such as dropdowns, collapsing navbars and modals.

Everything else is classes. A few you will use all the time:

Need Classes
centered page width container
layout grid row, col-md-6, col-lg-4 (12 columns; the suffix is a breakpoint)
spacing mt-3, mb-4, p-2, gap-3 (scale 0 to 5)
buttons btn btn-primary, btn btn-outline-secondary
card card, card-body, card-title
alert alert alert-success
form control form-control, form-label, form-check
A Bootstrap page: navbar, grid of cards, alert

(The preview needs internet access to download Bootstrap. Resize the window: the cards use 1, 2 or 3 columns depending on the width.)

Put the same tags once in your base template so every page inherits them (Template Inheritance). The responsive meta tag viewport is required for Bootstrap's breakpoints to work on phones.

CDN or local files?

A CDN is the least work and benefits from shared caching. Serving the files yourself from static/ (Static Files) avoids a third-party dependency (and a privacy or availability concern) and lets you pin the exact version. Either is fine; Bootstrap-Flask supports both.

Bootstrap-Flask

TEXT
pip install bootstrap-flask

Bootstrap-Flask (import name flask_bootstrap, do not confuse it with the older, unmaintained Flask-Bootstrap) is initialized like any extension: Bootstrap5(app). It adds:

  • {{ bootstrap.load_css() }} and {{ bootstrap.load_js() }}: the correct tags with integrity hashes, from a CDN by default or from local files with BOOTSTRAP_SERVE_LOCAL = True.
  • Macros in bootstrap5/form.html (render_form, render_field), bootstrap5/nav.html (render_nav_item), bootstrap5/utils.html (render_messages, render_icon), bootstrap5/pagination.html (render_pagination) and bootstrap5/table.html (render_table).

Rendering a form in one line

Without the extension, each field of a Flask-WTF form needs a <div>, a label, an input with the right classes and a loop over errors. render_form(form) writes all of that, including the hidden CSRF field and the is-invalid styling for fields that failed validation.

Python render_form, render_messages and render_nav_item

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The macros produce standard Bootstrap markup: form-control inputs, form-check for the checkbox, an is-invalid class plus an invalid-feedback message under each failed field, and alert alert-success boxes for flashed messages, whose category (success, danger, warning, info) selects the colour. render_nav_item('home', ...) creates a link from an endpoint name (like url_for) and marks it active for the current page.

render_form accepts options such as action, method, button_map={"submit": "success"} (choose the button colour), form_type="horizontal" (labels beside inputs), and render_kw. When you need full control of one field, use render_field(form.email) and write the rest of the layout by hand.

Tables and pagination

render_table(data, titles=[...]) turns a list of objects or dictionaries into a Bootstrap table, and render_pagination(pagination) renders page links from the Pagination object of db.paginate() (Queries and CRUD Views). Both accept options for striped rows, hover effects and action buttons. As with all Jinja output, values are escaped automatically.

Python render_table with data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Customizing and keeping control

Bootstrap sites tend to look alike, so make it yours:

  • Theme variables. Bootstrap 5.3 exposes CSS custom properties (--bs-primary, --bs-body-font-family). Override them in your own stylesheet after Bootstrap's: :root { --bs-primary: #7c3aed; } or set them on [data-bs-theme] for dark mode (<html data-bs-theme="dark">).
  • Your own CSS file loaded after Bootstrap for the few things you want different.
  • Utilities over custom CSS. Classes like d-flex, justify-content-between, text-truncate and visually-hidden cover most small layout needs.
  • Accessibility. Keep role="alert" on alerts, use aria-label on icon-only buttons, and keep visible focus styles. Bootstrap helps but does not make a page accessible by itself.
  • Weight. The full CSS is about 30 KB gzipped, plus 25 KB for JavaScript. Load the JavaScript only on pages that need it.

Bootstrap-Flask also supports Bootstrap 4 (Bootstrap4) and 5 (Bootstrap5) with macros under the matching folder. Choose 5 for new projects. If you prefer Tailwind or plain CSS, the Flask side is unchanged: only the templates differ. The portfolio project in Project: Single-Page Portfolio Site uses hand-written CSS if you want to compare.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which meta tag does Bootstrap's responsive behavior depend on?

    Without it, phones render the page as a wide desktop page and the breakpoints do not match the real screen width.
  2. 2. What does render_form(form) from Bootstrap-Flask do?

    The macro only renders markup. Validation still happens in your view with form.validate_on_submit().
  3. 3. How do you choose the colour of a flashed message alert with render_messages?

    flash(text, category) stores the category, and the macro turns it into alert-<category>.
  4. 4. Where should your own CSS go so that it can override Bootstrap?

    With equal specificity the later rule wins, so load your stylesheet after Bootstrap's.

Summary

  • Bootstrap styles pages through class names; add its CSS (CDN or local) and the viewport meta tag to your base template.
  • Bootstrap-Flask (Bootstrap5(app)) provides load_css/load_js and macros for forms, flash messages, nav items, tables and pagination.
  • render_form shows validation errors with is-invalid and invalid-feedback; the flash category picks the alert colour.
  • Customize with CSS variables and your own stylesheet loaded after Bootstrap; keep accessibility in mind.

Next: package and run your styled app in a container with Deployment, which now includes a step-by-step Docker section.