21.8. Styling Flask Templates

So far, we’ve used plain HTML for our sample form. However, in the last chapter, we applied some CSS rules to spice up how it looks.

A styled HTML form with a heading, background color, aligned fields, and large button.

One option for a styled form.

For our web applications, we definitely want to link a stylesheet to our HTML templates. To do this, we must save the .css file in a very specific place within our project.

21.8.1. The static Directory

By adding placeholders to our templates, we can change the content on a webpage based on a user’s actions. This makes the page dynamic. Style rules, on the other hand, remain fixed.

CSS code is an example of a static file. It does not change as the user interacts with the page. Other examples of static files include images, video clips, and JavaScript code.

In our Flask project, the templates folder holds all of the .html files for our website. We need to create a similar directory for our static files.

  1. In Visual Studio Code, use the terminal panel (or the buttons in the File Explorer pane) to create a new directory called static. The folder should be at the same level as hello.py and templates.

    A file tree showing the 'static' folder in the 'hello_flask' directory.

    The static folder in the hello_flask project tree.

  2. Inside the static folder, create a new file called style.css.

  3. Find the CSS code you used in the last chapter to style your form. Copy and paste that code into style.css.

  4. Save and commit your work.

21.8.2. Pro Tip

When we save a change to our HTML code, clicking the Refresh button in the browser displays the new layout. However, this doesn’t always work for changes made to the CSS. Browsers often save the stylesheet in memory to speed up reloading. If the browser continues to use the old code, we won’t be able to see our new styles.

To fix this, we need to force a clean reload of the page. For most browsers (like Firefox, Chrome, and Safari), hold down the Shift key and click Refresh. For Microsoft Edge, use the Control key plus Refresh.

21.8.3. Style Another Template

The form_results.html template also contains plain HTML.

  1. Add a <link> to the same stylesheet you used for your form.

  2. Navigate to the form in your browser. Fill in the fields and click Submit.

  3. Once on the results page, check to make sure your style rules were applied.

  4. If necessary, adjust your HTML and CSS code. Try to refine the appearance of the results page WITHOUT altering the look of the form.

21.8.4. Video Summary