外部CSS样式在HTML文件中不生效的问题排查与修复请求
问题:外部CSS样式无法作用于HTML文件的排查与解决
问题描述
我正在完成学校的HTML与CSS作业,此前编写的同类代码均可正常运行,但当前即便尝试了复制老师示例、参考过往项目等多种方法,外部CSS样式仍无法作用于HTML文件,希望能找到问题的解决办法。
预期效果:使页面标题区域背景为黑色、文字为白色且居中对齐。
原始代码
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <link rel="stylesheet" type="text/css" href="Webstyle.css"> <body> <div id="header"> <h1>Webpage Example</h1> </div> <div><img src="Myself.jpg" alt="Arata" height="300" class="center"> ##Align to the right</div> <br> <div> <p>・Self Introduction</p> <p>・My work</p> <p>・Contact</p> </div> <div> <h1>Self Introduction</h1> <p> My Name : ○○</p> <p>My nationality : ○○</p> <p>My age : ○○</p> <p>Current job : ○○</p> <p>Skill : Drawing</p> <p>Hobby : Vudeo recordings, Video games</p> <p>Favourite food :Fried food</p> </div> </body> </html>
CSS代码
@charset "UTF-8"; /* CSS Document */ #header{ background-colour : black; color : white; text-align:center; padding:5px; }
问题排查与解决
1. CSS属性拼写错误
CSS中background-colour是错误拼写,正确属性名为background-color(采用美式拼写),这个错误会直接导致背景色样式失效。
2. Link标签位置错误
外部样式表的<link>标签必须放置在<head>标签内部,你当前将其放在了<head>闭合之后、<body>之前,不符合HTML规范,会影响浏览器对样式表的加载解析。
修正后的代码
修正后的HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="Webstyle.css"> </head> <body> <div id="header"> <h1>Webpage Example</h1> </div> <div><img src="Myself.jpg" alt="Arata" height="300" class="center"> <!-- 改为右对齐 --></div> <br> <div> <p>・Self Introduction</p> <p>・My work</p> <p>・Contact</p> </div> <div> <h1>Self Introduction</h1> <p> My Name : ○○</p> <p>My nationality : ○○</p> <p>My age : ○○</p> <p>Current job : ○○</p> <p>Skill : Drawing</p> <p>Hobby : Video recordings, Video games</p> <p>Favourite food :Fried food</p> </div> </body> </html>
修正后的CSS
@charset "UTF-8"; /* CSS Document */ #header{ background-color: black; color: white; text-align:center; padding:5px; }
额外检查项
- 确认CSS文件名
Webstyle.css与HTML中的引用完全一致(注意大小写,Linux等系统对文件名大小写敏感) - 确保CSS文件与HTML文件处于同一目录,若不在同一目录需填写正确的相对路径(如
./css/Webstyle.css)
内容的提问来源于stack exchange,提问作者Mabuchi Arata
相关产品推荐
相关产品推荐

