VS Code中CSS媒体查询不生效:背景色未变化求解决方案
解决CSS媒体查询未生效的问题
你的媒体查询未生效存在两个关键错误,修复后即可正常触发样式:
错误1:媒体查询语法缺失and
CSS规范中,媒体类型(如screen)与媒体特性(如(max-width: 300px))之间必须用and连接,否则浏览器无法正确解析条件。
错误2:选择器匹配错误
你使用了.body类选择器,但实际要修改的是<body>标签元素,应该直接使用body标签选择器(不带前缀点)。
修复后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" type="image/png" sizes="32x32" href="images/favicon-32x32.png"> <title>Frontend Mentor | QR code component</title> <style> /* 修复后的媒体查询 */ @media screen and (max-width: 300px) { body { background: blue; } } .attribution { font-size: 11px; text-align: center; font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; background-color: rgb(244, 244, 244); margin-top: 1%; margin-left: 30%; margin-right: 30%; margin-bottom: 1%; border-radius: 10px; width: 300px; padding: 10px; padding-right: 20px; } .attribution a { color: hsl(228, 45%, 44%); } body { background-color: red; } .fade { color: #a9a9b1a7; font-size: 14px; } .QR { width: 310px; height: 320px; border-radius: 10px; margin:0% } </style> </head> <body> <div class="attribution"> <img src="images/image-qr-code.png" alt="img" class="QR"> <h1>Improve your front-end skills by building projects </h1> <h2 class="fade">Scan the QR code to visit Frontend Mentor and take your coding skills to the next level Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>. Coded by <a href="#">lalith prasad</a>.</h2> </div> </body> </html>
测试提示
可以用浏览器开发者工具的设备模拟功能,将屏幕宽度调至300px及以下,即可看到页面背景色变为蓝色。
内容的提问来源于stack exchange,提问作者Pentakota Lalith Prasad
相关产品推荐
相关产品推荐

