问题背景

前端小白,刚刚接触 html 正对着教程搞到外联 css 时,发现 css 样式并没有加载。

原因查找

  • 检查 html 5 代码,无误

    <head>
        <meta charset="UTF-8">
        <title>Practise Html 5</title>
        <link rel="stylesheet" type="text/css" href="css/asdd.css" charset="UTF-8">
    </head>
    
  • css 里的代码也正常

    body {
        background:black;
        color:white;
    }
    
  • 去浏览器网页,右键 - 检查 (Ctrl + Shift + I),发现报错信息,说我的样式引用 css 的 MIME type 为 ‘text/html’ ,但奇怪的是我的代码里明确给服务器指定了类型为 type=“text/css”

    Refused to apply style from ‘http://localhost:63342/html_file/css/asdd.css’ because its MIME type (‘text/html’) is not a supported stylesheet MIME type, and strict MIME checking is enabled.

解决问题

  • 因为步骤是完全照着教程来的,唯一和教程里不一样的就是编辑器,我用的是Pycharm。于是打开 Notepad++,新建文档, 把 css 里的代码复制过去,文件存为 .css 再将 这个 css 文件导入到Pycharm 的 Project 里,再外联,发现这一次加载成功了。

  • 对比两个 css 文件的差异,发现我在 Pycharm 里的 css 文件名称少了 .css 这个后缀。原因是在新建文档时我只输入了文档名称,然后选择了在 Pycharm 里将这个文件以 css 类型打开,实际上这个文档被默认格式为 html。


  • 重命名给 Pycharm 里的 css 文件加上 .css 后缀后 css 样式引用成功。

总结

在 Pycharm 新建 css 文件时,命名要输 ‘xxxx.css’ 直接生成 css 文件


更多推荐

解决 Html 5 外联 css 无法加载因为 its MIME type ('text/html') is not a supported