首页 > 解决方案 > CSS 文件未链接到 HTML 文件,路径和顺序似乎正确

问题描述

我的 layout.html 文件位于“templates”目录中,styles.css 文件位于“static”目录中。两者都在我的名为“books-cs50w”的项目文件夹中。虽然不起作用。我可能已经阅读了关于绝对路径和相对路径的所有 google-able 帖子,但由于某种原因,我的 css 并未应用于我的 layout.html。我将它放在引导样式表的底部和顶部,以确保它不会被覆盖。为了测试实际的 CSS,我将代码直接粘贴到 layout.html 文件中的 -tags 中——它可以工作。但是无论我在外部做什么 - 它都不会读取它。

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
<link rel="canonical" href="https://getbootstrap.com/docs/4.0/examples/sign-in/">

<!-- Bootstrap core CSS -->
<link rel="stylesheet" 
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384- Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="https://getbootstrap.com/docs/4.0/dist/css/bootstrap.min.css" rel="stylesheet">

<!-- Custom styles for this template -->
<link href="https://getbootstrap.com/docs/4.0/examples/sign-in/signin.css" rel="stylesheet">
<link href="/static/styles.css" rel="stylesheet" >
</head>

测试它的 CSS 是:

img  {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
}

h1, h2 {
 color: red;
 background-color: green;
}

body, head {background-color: green;
  color: yellow;
}

在此处输入图像描述

标签: htmlcss

解决方案


您需要通过添加到您的 css 路径来从当前templates文件夹../上一层,现在您已经上一层并且当前位于主books-cs50w项目文件夹中,您只需导航到您的static文件夹并访问 css 文件。

更改此行:

<link href="/static/styles.css" rel="stylesheet" >

对此:

<link href="../static/styles.css" rel="stylesheet" >

推荐阅读