You need to enable JavaScript to run this app. 响应式设计异常:媒体查询调窗口生效,开发者工具模拟设备时失效
优惠活动
大模型
产品
解决方案
定价
更多

响应式设计异常:媒体查询调窗口生效,开发者工具模拟设备时失效

问题根因定位
  • CSS大括号配对错误导致样式块逻辑完全错位:原代码的媒体查询块中,.controls选择器开启的样式块从未闭合,媒体查询块提前结束,后续所有通用样式(游戏网格、开始按钮、方块样式、动画等)全部被浏览器错误解析为.controls的嵌套子规则,仅在视口宽度≥768px时生效。这完全匹配遇到的现象:大窗口调整时视口大于768px,样式生效;开发者工具模拟小屏时视口小于768px,所有通用样式失效,显示异常。
  • 媒体查询内存在非法的选择器嵌套:把.mobile的样式写在.controls的规则内部,普通CSS不支持原生选择器嵌套,导致.mobile的大屏字体规则完全无法生效。
  • 固定尺寸元素未做响应式适配:.nokia元素写死700px宽度、983px高度,小屏视口下会直接溢出;所有绝对定位元素未给父容器.mobile设置position: relative,位置随视口尺寸变化产生偏移。
  • 代码语法笔误:.apple类的background-color属性值后面错写成分号;viewport meta标签位置不规范,缺少字符集声明,容易导致设备模拟时缩放逻辑异常。
修复方案
  • 修正大括号配对逻辑:把媒体查询块内的所有规则的大括号配对补全,把后续的通用样式(网格、按钮、动画等)从嵌套块里移出来,放在全局作用域,保证任何视口尺寸下都能生效。
  • 移除非法的选择器嵌套:把.mobile的大屏样式平级放在媒体查询块内,和.controls的样式并列。
  • 给.mobile容器加position: relative作为绝对定位子元素的参考父级;把固定宽度的元素用min()函数设置最大宽度,保证小屏下自动适配视口宽度,不溢出。
  • 修正CSS笔误,把viewport和字符集meta标签移到head最开头,补全HTML的根标签结构。
  • 把固定像素的游戏方块尺寸改成百分比相对单位,保证网格缩放时方块自动适配大小。
修正后的核心代码

HTML结构

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1" name="viewport" />
    <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class='mobile'>
    <h1 id="title">Snake</h1>
    <div class="info">
      <button id="start">Lets go!</button>
      <h2>Score <span id="score"></span></h2>
    </div>
    <div class="grid"></div>
    <div class="nokia"></div>
  </div>
  <div class="controls">
    <h3>Controls</h3>
      <ul><span class="direction">Up</span> - Up arrow key</ul>
      <ul><span class="direction">Right</span> - Right arrow key</ul>
      <ul><span class="direction">Down</span> - Down arrow key</ul>
      <ul><span class="direction">Left</span> - Left arrow key</ul>
  </div>
  <script src="main.js"></script>
</body>
</html>

CSS样式

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.mobile {
  position: relative;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #12c258;
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  font-size: 60%;
}

#title {
  color: #fff;
  margin-top: 1rem;
}

.nokia {
  position: absolute;
  top: 190px;
  display: block;
  width: min(700px, 90vw);
  aspect-ratio: 700/983;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.controls {
  text-align: center;
  padding: 2px;
  height: 125px;
  background-color: #12c258;
  color: #fff;
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}

.direction {
  font-weight: bold;
}

/* 修正后:媒体查询内的规则平级,大括号配对完整 */
@media only screen and (min-width: 768px) {
  .controls {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 2rem;
    height: 70px;
    font-size: 100%;
  }
  .mobile {
    font-size: 100%;
  }
}

.grid {
  position: absolute;
  top: 420px;
  z-index: 9999;
  display: flex;
  flex-wrap: wrap;
  width: min(200px, 60vw);
  aspect-ratio: 1/1;
  border: 2px solid rgba(0, 0, 0, 0.5);
  background-color: #12c258;
}

.info {
  position: absolute;
  z-index: 9999;
  top: 663px;
  text-align: center;
}

h2 {
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  font-size: 15px;
  position: absolute;
  top: 90px;
  left: -60px;
}

button {
  position: absolute;
  left: -92px;
  height: 64px;
  width: 172px;
  border-style: solid;
  border-radius: 50%;
  text-align: center;
  display: inline-block;
  font-size: 20px;
  outline: none;
}

button:active {
  transform: translateY(2px);
}

.square {
  width: 10%;
  height: 10%;
}

.snake {
  background-color: #fff;
  border-radius: 50%;
}

.apple {
  background-color: red;
  border-radius: 20%;
  box-shadow: 0 0 0 0 rgba(0, 0, 0, 1);
  transform: scale(1);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(0.7);
    box-shadow: 0 0 0 0 rgba(0, 0, 0, 0.7);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(0.7);
  }
}

JavaScript逻辑

const grid = document.querySelector(".grid");
const startButton = document.getElementById("start");
const scoreDisplay = document.getElementById("score");
let squares = [];
let currentSnake = [2, 1, 0];
let direction = 1;
const width = 10;
let appleIndex = 0;
let score = 0;
let intervalTime = 1000;
let speed = 0.9;
let timerId = 0;

function createGrid() {
  for (let i = 0; i < width * width; i++) {
    const square = document.createElement("div");
    square.classList.add("square");
    grid.appendChild(square);
    squares.push(square);
  }
}
createGrid();

currentSnake.forEach(index => squares[index].classList.add("snake"));

function startGame() {
  currentSnake.forEach(index => squares[index].classList.remove("snake"));
  squares[appleIndex].classList.remove("apple");
  clearInterval(timerId);
  currentSnake = [2, 1, 0];
  score = 0;
  scoreDisplay.textContent = score;
  direction = 1;
  intervalTime = 1000;
  generateApple();
  currentSnake.forEach(index => squares[index].classList.add("snake"));
  timerId = setInterval(move, intervalTime);
}

function move() {
  if (
    (currentSnake[0] + width >= width * width && direction === width) ||
    (currentSnake[0] % width === width - 1 && direction === 1) ||
    (currentSnake[0] % width === 0 && direction === -1) ||
    (currentSnake[0] - width < 0 && direction === -width) ||
    squares[currentSnake[0] + direction].classList.contains("snake")
  )
    return clearInterval(timerId);

  const tail = currentSnake.pop();
  squares[tail].classList.remove("snake");
  currentSnake.unshift(currentSnake[0] + direction);

  if (squares[currentSnake[0]].classList.contains("apple")) {
    squares[currentSnake[0]].classList.remove("apple");
    squares[tail].classList.add("snake");
    currentSnake.push(tail);
    generateApple();
    score++;
    scoreDisplay.textContent = score;
    clearInterval(timerId);
    intervalTime = intervalTime * speed;
    timerId = setInterval(move, intervalTime);
  }

  squares[currentSnake[0]].classList.add("snake");
}

function generateApple() {
  do {
    appleIndex = Math.floor(Math.random() * squares.length);
  } while (squares[appleIndex].classList.contains("snake"));
  squares[appleIndex].classList.add("apple");
}
generateApple();

function control(e) {
  if (e.keyCode === 39) {
    direction = 1;
  } else if (e.keyCode === 38) {
    direction = -width;
  } else if (e.keyCode === 37) {
    direction = -1;
  } else if (e.keyCode === 40) {
    direction = +width;
  }
}
document.addEventListener("keyup", control);
startButton.addEventListener("click", startGame);
验证方式
  • 切换浏览器开发者工具的设备模拟模式,调整视口宽度,即可看到媒体查询规则在任意尺寸下正常生效
  • 小屏模式下所有元素会自动适配视口宽度,不会出现溢出、错位、样式失效的问题

内容的提问来源于stack exchange,提问作者Ray U

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.24 04:45:05