已正确链接CSS但样式规则完全不生效,该如何排查解决?
排查解决步骤
- 检查CSS文件是否被正常加载
按下F12打开浏览器开发者工具,切换到「网络」面板,刷新页面后筛选CSS类请求,查看style.css的请求状态:- 若状态码为404:确认服务器上CSS文件名是否和HTML中
href="style.css"完全一致,注意Linux服务器对文件名大小写敏感,需检查是否出现Style.css、style.css.txt这类命名错误,同时确认文件确实和index.html放在同一目录下。 - 若状态码为200但样式不生效:查看该请求的响应头,确认
Content-Type值为text/css,如果值为text/plain或其他内容,说明服务器未正确配置CSS文件的MIME类型,到服务器配置文件中添加对应规则即可解决。
- 若状态码为404:确认服务器上CSS文件名是否和HTML中
- 排除浏览器缓存干扰
按下Ctrl+F5(Mac设备为Cmd+Shift+R)强制刷新页面,或者在开发者工具「网络」面板勾选「禁用缓存」后再刷新,避免浏览器加载旧的缓存文件。 - 验证CSS规则匹配情况
如果CSS文件已经正常加载,在开发者工具「元素」面板随意选中页面内的h1标签,查看右侧样式栏是否出现你写的.brand、h1相关规则,若规则存在但被划掉才需要调整优先级,你提供的CSS本身没有语法错误,不需要修改内容。
参考代码
HTML代码
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <title>home</title> </head> <body> <header> <h1 class = "brand">(coming soon)</h1> <h3 class = "brand">-Websites, presenting your company to the world-</h3> <nav> <ul> <li><a href="./Codecademy/index">Playing around with coding course</a></li> <li><a href="portfolio">Portfolio</a></li> <li><a href="prices">Prices</a></li> <li><a href="team">Team</a></li> <li><a href="contact">Contact</a></li> </ul> </nav> </header> <main> <h1>Elegant Interactive Websites</h1> <img src="Media/Website_image.jpeg" alt="" style = "width: 500px; height: 300px;"> <h1>Beautiful Graphic Design</h1> <img src="Media/GraphicDesign_image.png" alt="" style = "width: 500px; height: 300px;"> <h1>Seamless Animations</h1> <img src="Media/Animation.jpeg" alt="" style = "width: 500px; height: 300px;"> <h1>Reliable Databases</h1> <img src="Media/Data base.jpeg" alt="" style = "width: 500px; height: 300px;"> </main> <footer> <p>Code written in HTML, (some CSS) and JavaScript</p> </footer> </body> </html>
CSS代码
html, body { margin: 0; padding: 0; background-color: black; } a { color: red; } .brand{ color: red; font-size: 300px; font-family: cursive; background-color: black; } h1{ color: red; font-size: 300px; background-color: black; }
内容的提问来源于stack exchange,提问作者Jakob
相关产品推荐
相关产品推荐

