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

全屏状态下Grid布局显示分裂问题求助

问题:Grid布局全屏时列分离,非全屏显示正常

用JavaScript实现的Grid布局,单元格鼠标悬停会变色,但全屏窗口下网格变成四个分离的列;非全屏窗口下显示正常,是无间距的标准网格(符合预期)。

效果对比

  • 全屏异常效果:
    全屏下的网格间距问题
  • 正常期望效果:
    非全屏下的标准网格

原始代码

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Etch N Sketch</title>
</head>
<body>
<div class="container" id="container"></div>
<script src="script.js"></script></body>
</html>

JavaScript

const board = document.getElementById("container");
for (x=0; x <= 15; x++) {
    const cell = document.createElement('div');
    cell.className = "cells";
    cell.setAttribute("style", "height: 200px; width: 200px; color: black;");
    cell.style.backgroundColor = "blue";
    cell.style.border = "solid 2px";
    cell.style.borderColor = "black";
    board.style.columnGap = "0px";
    board.style.display ="grid";
    board.style.gridTemplateColumns = "auto auto auto auto";
    board.appendChild(cell);
    cell.addEventListener("mouseover", change = () => 
    cell.style.backgroundColor = "red")
    cell.addEventListener("mouseout", reset = () => cell.style.backgroundColor = "blue")
} 

问题原因

你给Grid容器设置了gridTemplateColumns: "auto auto auto auto",auto表示列宽由内容和容器可用空间共同分配。当窗口全屏时,容器宽度远大于4个单元格(含边框)的总宽度,Grid会把剩余空间平均分配到列之间,导致出现明显间距;非全屏时容器宽度刚好适配单元格总宽度,所以没有间距。

另外,循环内重复设置容器的Grid样式(执行16次)属于冗余操作,且单元格边框未纳入宽高计算,可能导致总宽度溢出。

修复方案

修改后的JavaScript代码

const board = document.getElementById("container");
// 容器Grid样式仅初始化一次
board.style.display = "grid";
board.style.gridTemplateColumns = "repeat(4, 200px)"; // 固定列宽与单元格一致
board.style.columnGap = "0px";
board.style.rowGap = "0px"; // 确保行间距也为0

for (let x = 0; x <= 15; x++) {
    const cell = document.createElement('div');
    cell.className = "cells";
    // 用box-sizing让边框包含在宽高内,避免溢出
    cell.setAttribute("style", "height: 200px; width: 200px; color: black; box-sizing: border-box;");
    cell.style.backgroundColor = "blue";
    cell.style.border = "solid 2px black"; // 合并边框设置
    board.appendChild(cell);
    // 简化事件监听写法
    cell.addEventListener("mouseover", () => cell.style.backgroundColor = "red");
    cell.addEventListener("mouseout", () => cell.style.backgroundColor = "blue");
}

关键修改点

  1. 固定列宽:用repeat(4, 200px)替代auto auto auto auto,让每列宽度和单元格固定宽度一致,避免剩余空间分配导致的间距。
  2. 样式初始化优化:将容器的Grid样式移到循环外,仅设置一次,避免冗余操作。
  3. 边框纳入宽高:添加box-sizing: border-box,让单元格边框包含在200px的宽高内,防止总宽度溢出。
  4. 简化代码:合并边框属性设置,去掉事件监听的多余变量声明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 12:18:20