skip to Main Content

I am trying to connect some CSS code to some html code. This code is part of a bigger project that’s why I imported a lot of stuff at the top but I am stuck on this simple step for some reason. Whenever I run my code it shows just the html on the website without the CSS. Sorry if this is a super obvious question I am still very new to coding.

I tried various ways of connecting it but it is not working.

import os
from flask import Flask, request, redirect, session

app = Flask(__name__)


@app.route('/')
def home():
    page = """
    <html>
    <head>
     <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Stef LinkTREE</title>
  <link href="style.css" 
    rel="stylesheet" type="text/css" />
    </head>
    <body>
    <p>SPADE</p>

    </body>
    </html>

    """
    return page


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)
html, body {
  height: 100%;
  width: 100%;
  color:black;
}

p{
   font-family: sans-serif;
  font-size: 28px;
  color: white;
  text-align: center;
}

2

Answers


  1. When using Flask you have to use the ‘static’ directory.

    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css.css') }}">
    

    Documentation:

    https://exploreflask.com/en/latest/static.html
    
    Login or Signup to reply.
  2. If you want to stick to HTML only, regardless which technology you are relying on, just do it static like ‘./my-site/style/something.css’ URL formation and it will always work. Note that the ‘./’ base always points to your HTML file URL location.

    Diagnostics: Use network tab in browser developer tools and I am sure you will see your call to the CSS is failing for a wrong URL/location. Click the request to see where that URL points to and fix your HTML LINK code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search