Answer a question

I'm learning Flask and I have this basic web application. I'm using Bootstrap 5 and I noticed that if I load the Bootstrap stylesheet my custom CSS does not work (if I remove Bootstrap stylesheet it works fine).

I have this folder structure:

flaskWebsite
         |
         |__pycache__
         |
         |templates
                 |index.html
                  ...
         |static
               |
               |main.css
               |main.js
         |venv 
         |
         |app.py

         

Here is some relevant code:

app.py

@app.route("/")
def index():
    return render_template('index.html')

index.html

<head>
        <title>Home</title>
        <!--Custom CSS-->
        <link rel="stylesheet" href="{{url_for('static', filename='main.css')}}">

        <!-- Latest compiled and minified Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    </head>

I tryed to put bootstrap.min.css (downloaded from Bootstrap) into the static folder, but it doesn't change.

Can anyone explain me why does this happen and how can I fix it?

Answers

It is called precedence, whenever you have multiple stylesheets in the same html file, if some of them contain elements with the same specificity, the last one will be applied. In your case, Bootstrap css is probably overriding your custom css. Try placing custom css after bootstrap one like this:

<head>
        <title>Home</title>

        <!-- Latest compiled and minified Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <!--Custom CSS-->
        <link rel="stylesheet" href="{{url_for('static', filename='main.css')}}">
</head>
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐