Search code examples
pythoncssdjangodjango-templatesdjango-staticfiles

Django: How to use CSS that's in another file?


This is probably a stupid question. I'm new to Django and I was wondering how to use CSS when it is in a different file.

Right now, my file paths looks like this:

CSS: web/static/web/style.css

HTML: web/templates/web

My HTML file looks like this:

{% load static %}

<!--HTML-->
<body>
    <div class="topnav">
        <a class="active" href="/">Home</a>
        <a href="/donate">Donate</a>
    </div>
</body>

My CSS looks like this:

  .topnav {
    background-color: #333;
    overflow: hidden;
  }
 
  .topnav a {
    float: left;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
  }
  
  .topnav a:hover {
    background-color: #ddd;
    color: black;
  }
 
  .topnav a.active {
    background-color: #04AA6D;
    color: white;
  }

How can I get the HTML to use the CSS from a different file?


Solution

  • add a <head>…</head>tag and type <link rel="stylesheet" href="static/web/style.css"/> inside the <head>…</head> tag. Make sure the <head>…</head> is outside the <body>…</body> tag. Here is the new code.

    <!DOCTYPE html>
    <html>
     <head>
      <link rel="stylesheet" href="static/web/style.css"/>
      <!--other head contents like title and meta tag goes here-->
     </head>
     <!--HTML-->
     <body>
        <div class="topnav">
            <a class="active" href="/">Home</a>
            <a href="/donate">Donate</a>
        </div>
     </body>
    </html>