Flex布局模式下如何在区块上方居中显示文本——以3*4网格上方居中"Game Over"文本为例
Solution: Center "Game Over" Above Your 3x4 Flex Grid
Got it, let's get that "Game Over" text sitting nicely centered above your memory game grid using Flexbox. Here's a straightforward, clean approach that works with your existing CSS:
Step 1: Adjust Your HTML Structure
First, wrap your game grid in a parent container that will hold both the title and the grid. This lets us use Flexbox to arrange them vertically:
<div class="game-container"> <h1 class="game-over">Game Over</h1> <div class="memory-game"> <!-- Your 3x4 grid cards go here --> </div> </div>
Step 2: Update Your CSS
We'll tweak the existing styles and add a few new rules to handle centering and layout:
* { padding: 0; margin: 0; box-sizing: border-box; } body { font-family: 'Lato', sans-serif; height: 100vh; display: flex; align-items: center; justify-content: center; /* Add this to center the game container horizontally */ background-image: linear-gradient(to right top, #9200ff, #8c1cf8, #8729f0, #8232e8, #7e39e0); } /* New parent container for title + grid */ .game-container { display: flex; flex-direction: column; /* Stack title and grid vertically */ align-items: center; /* Center both items horizontally */ } /* Style the "Game Over" text */ .game-over { color: #ffffff; font-size: 2.5rem; margin-bottom: 2rem; /* Add space between title and grid */ text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3); /* Optional: Add depth to the text */ } .memory-game { width: 640px; height: 640px; /* Remove margin:auto since game-container handles centering now */ display: flex; flex-wrap: wrap; perspective: 1000px; }
How It Works
- The
game-containeracts as a vertical Flex container, so the title and grid stack on top of each other.align-items:centerensures both are perfectly centered horizontally. - We added
justify-content:centerto thebodyto make sure the entire game container is centered vertically and horizontally on the page (your original code only handled vertical centering). - The
game-overstyles add visual separation from the grid and make the title pop against your gradient background.
内容的提问来源于stack exchange,提问作者Cooldudewhoprograms
相关产品推荐
相关产品推荐

