全屏状态下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"); }
关键修改点
- 固定列宽:用
repeat(4, 200px)替代auto auto auto auto,让每列宽度和单元格固定宽度一致,避免剩余空间分配导致的间距。 - 样式初始化优化:将容器的Grid样式移到循环外,仅设置一次,避免冗余操作。
- 边框纳入宽高:添加
box-sizing: border-box,让单元格边框包含在200px的宽高内,防止总宽度溢出。 - 简化代码:合并边框属性设置,去掉事件监听的多余变量声明。
内容的提问来源于stack exchange,提问作者seemwavy
相关产品推荐
相关产品推荐

