CSS Grid技术问题:如何将元素移至网格单元格底部
Hey there! Let's get your text positioned correctly while keeping that full-screen adaptive grid. Here's how you can adjust your code:
First, Update Your Grid Container CSS
Your current display: inline-block isn't leveraging CSS Grid's full power. Let's switch to proper grid layout to ensure the rows evenly fill the entire screen height:
.grid-container { background-color: rgb(222, 224, 202); height: 100vh; /* Using viewport height ensures it fills the screen */ position: fixed; top: 0; left: 0; right: 0; bottom: 0; display: grid; /* Switch to CSS Grid for proper row control */ grid-template-rows: 1fr 1fr 1fr; /* Split height equally into 3 rows */ }
Position Text at the Bottom of a Grid Item
To move text like "hi" to the bottom of its cell, use Flexbox inside the grid item. This gives you precise control over content alignment without breaking the grid structure:
.grid-item1 { padding: 1em; border: 1px solid black; display: flex; /* Enable flexbox for internal content alignment */ flex-direction: column; /* Stack content vertically */ justify-content: flex-end; /* Push content to the bottom of the cell */ } /* Clean up other grid items (fixed height is no longer needed) */ .grid-item2 { padding: 1em; border: 1px solid black; } .grid-item3 { padding: 1em; border: 1px solid black; text-align: center; }
Example HTML Structure
Here's a sample HTML snippet to pair with the updated CSS:
<div class="grid-container"> <div class="grid-item1">hi</div> <div class="grid-item2">i'm andrew camilleri</div> <div class="grid-item3">Your portfolio content here</div> </div>
Key Notes
- Using
1fringrid-template-rowsensures each row takes an equal share of the container's height, making it fully adaptive across all screen sizes. - Flexbox inside the grid item lets you easily align content to the top, bottom, or center without messing with the overall grid layout.
- Removing the fixed
height: 33%from grid items is better because CSS Grid handles row heights automatically, preventing layout glitches on smaller devices.
This setup will keep your grid filling the entire screen, move "hi" right above "i'm andrew camilleri" at the bottom of its cell, and adapt smoothly to different device sizes.
内容的提问来源于stack exchange,提问作者user10997484

