如何用CSS Grid实现2048游戏中4×4网格的水平垂直居中
Got it, let's get that 4x4 grid perfectly centered inside your game-container! Since you're already working with CSS Grid for the game board, we can use modern layout properties to make this straightforward. Here are a few reliable approaches tailored to your existing structure:
game-container (Cleanest & Most Modern) This method leverages CSS Grid's built-in centering capabilities, which pairs nicely with your existing grid-based game board.
First, ensure your game-container takes up the space you need (you mentioned it should adapt to the browser window, so we'll use viewport units here). Then add a single property to handle both horizontal and vertical centering:
/* Make game-container fill the entire viewport */ .game-container { width: 100vw; height: 100vh; margin: 0; padding: 0; /* Center the child .game element */ display: grid; place-items: center; } /* Your existing 4x4 grid setup for the game board */ .game { display: grid; grid-template-columns: repeat(4, 1fr); grid-template-rows: repeat(4, 1fr); gap: 10px; /* Optional: add spacing between cells */ width: 320px; /* Set a fixed size for your game board (adjust as needed) */ height: 320px; } .game-cell { background-color: #f0f0f0; border-radius: 6px; /* Add cell styling (like numbers later) here */ }
The place-items: center property is a shorthand for align-items: center and justify-items: center—it instantly centers the .game element within the grid container.
game-container If you prefer Flexbox over Grid for the container, this works just as well:
.game-container { width: 100vw; height: 100vh; margin: 0; padding: 0; display: flex; justify-content: center; /* Horizontal centering */ align-items: center; /* Vertical centering */ } /* Keep your existing .game and .game-cell styles the same as above */
Flexbox is widely supported and intuitive for single-axis alignment, but Grid's place-items is a bit more concise for dual-axis centering.
If you need to support very old browsers that don't handle Grid/Flexbox well, this absolute positioning trick works reliably:
.game-container { position: relative; width: 100vw; height: 100vh; } .game { position: absolute; top: 50%; left: 50%; /* Shift the element back by half its own size to center it */ transform: translate(-50%, -50%); /* Your existing game grid styles here */ }
Quick Notes:
- Adjust the
widthandheightof.gameto fit your design (you can use relative units like80vwinstead of fixed pixels for responsive sizing). - If your
game-containerdoesn't need to fill the entire viewport, just remove thewidth: 100vwandheight: 100vhlines—make sure the container has a defined size (either explicit or from its parent) for centering to work.
内容的提问来源于stack exchange,提问作者Fallen Apart

