Ask AI Assistant

Download source code

In this lesson, we’ll cover how to include static files in our Flask application. We’ll also begin to enhance the appearance of our website by adding CSS styles.

What are static files?

Static files are files that are served directly to the client without any processing by the server. These files are required by the web browser to display the website and include images, CSS files, JavaScript files, and other types of files. Many web frameworks, including Flask, have built-in support for serving static files. In Flask, static files are typically stored in a folder called “static” inside the application folder.

Let’s create a new folder for our static files.

Creating a CSS file

Let’s add some style to our website. To customize the appearance of HTML elements on our website, we can use CSS files. CSS stands for Cascading Style Sheets, and it allows us to define styles for HTML elements and apply them to multiple elements at once. For example, we can define a style for all paragraphs on the page and apply it to all paragraphs at once. By using CSS, we can create a consistent and visually appealing design for our website.

We’ll create a CSS file called “style.css” in the static folder. We’ll add the following CSS code to the file.

First we’ll define a style for the body element. We’ll set the background color to light gray and the font family to sans-serif. We’ll also set the font size to 16 pixels.

To apply styles to our website using CSS, we need to connect the CSS file to the base template. We can do this by adding a link tag to the head section of the template. The link tag has several attributes, including the href attribute, which specifies the path to the CSS file. In this case, the value of the href attribute is “/static/style.css”. The rel attribute should be set to “stylesheet”.

In the previous lesson, we used the url_for function to generate URLs for pages of the store, and this function can also be used to generate the path to static files, but for simplicity, we’ll use a hardcoded path in this example.

Let’s refresh the page. We can see that the website’s appearance has been updated. The background color is now a light shade of gray, and the font used on the website is sans-serif. This means that the font does not have serifs, which are the small lines at the end of strokes in letters.

Let’s continue to add more styles to the website in the next lesson. We are going to continue to do this in the next lesson.