You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML/CSS/JS开发2048时内容更新致Div偏移问题求助

嘿,我来帮你搞定这个2048网格错位的问题!先给你拆解下问题根源,再直接上修复后的完整代码。

问题根源分析

你的网格错位主要是三个原因叠加导致的:

  1. inline-block的默认空白坑:用display: inline-block排列格子时,HTML里的换行、空格会被解析成空白字符,占据额外宽度,导致总宽度超出容器触发换行。
  2. 容器宽度计算错误:你的.gridd设置了width:340px+padding:15px,实际内部可用宽度是340-15*2=310px,但每个格子是100px+左右各5pxmargin,三个格子总宽度是100*3+5*2*3=330px,直接超过了容器宽度,必然错位。
  3. 嵌套绝对定位的混乱:.gridd和.wrapper都用了position:absolute,这种嵌套会导致容器尺寸计算异常,尤其是.gridd的margin:auto在没设置top/right/bottom/left的情况下根本无法生效,布局自然乱套。

修复方案 & 完整代码

我用现代Flexbox布局替代inline-block,同时修正了宽度计算和定位逻辑,还顺便优化了JS的随机数重复问题:

修复后的HTML(仅格式化,结构不变)

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>2048</title>
</head>
<body>
    <div class="wrapper">
        <div class="gridd">
            <div><h1></h1></div>
            <div><h1></h1></div>
            <div><h1></h1></div>
            <div><h1></h1></div>
            <div><h1></h1></div>
            <div><h1></h1></div>
            <div><h1></h1></div>
            <div><h1></h1></div>
            <div><h1></h1></div>
        </div>
    </div>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>

修复后的CSS

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box; /* 核心:让padding/border算入元素宽度,避免计算混乱 */
}

body {
    background-color: #C2C2C2;
    min-height: 100vh;
    display: flex; /* 让游戏网格在页面垂直水平居中 */
    justify-content: center;
    align-items: center;
}

h1 {
    font-family: Asap, sans-serif;
    font-size: 24pt;
    text-align: center;
    color: white;
}

.gridd {
    width: fit-content; /* 容器自适应内容宽度,彻底告别手动计算宽度的麻烦 */
    background-color: #B4B4B4;
    border-radius: 15px;
    padding: 15px;
    display: flex; /* 用Flexbox排列格子 */
    flex-wrap: wrap; /* 超过宽度自动换行 */
    gap: 10px; /* 用gap精准控制格子间距,替代margin避免重复计算 */
}

.gridd > div {
    width: 100px;
    height: 100px;
    background-color: #787878;
    border-radius: 15px;
    display: flex; /* 让数字在格子里精准居中 */
    align-items: center;
    justify-content: center;
}

修复后的JS(解决随机数重复问题)

function getRandomInt(max) {
    return Math.floor(Math.random() * Math.floor(max));
}

var y = document.getElementsByTagName("H1");
// 确保生成两个不同的随机位置,不会出现只显示一个2的情况
let firstPos = getRandomInt(9);
let secondPos;
do {
    secondPos = getRandomInt(9);
} while (secondPos === firstPos);

y[firstPos].innerHTML = 2;
y[secondPos].innerHTML = 2;

修复关键点说明

  • box-sizing: border-box:彻底解决padding和border导致的宽度计算偏差问题。
  • Flexbox布局:消除inline-block的空白间距,用gap统一控制格子间距,布局更稳定。
  • 精准居中:用Flex替代margin-top:35%的近似居中,数字在格子里的位置永远准确。
  • 随机数优化:保证每次加载都能生成两个不同的初始数字2,避免重复覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:59:05