How to vertically center align an element to the last row in CSS Grid?
P粉520204081
2023-08-22 15:57:06
<p>I'm laying out some items using a CSS grid, like this...</p>
<p><br /></p>
<pre class="brush:css;toolbar:false;">#container {
display: grid;
grid-template-columns: 16.666% 16.666% 16.666% 16.666% 16.666% 16.666%;
}
.item {
background: teal;
color: white;
padding: 20px;
margin: 10px;
}</pre>
<pre class="brush:html;toolbar:false;"><div id="container">
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
<div class="item">item</div>
</div></pre>
<p><br /></p>
<p>How can I make the last row centered instead of left aligned? I can't guarantee the number of items, so hopefully the layout will work with any number of items. </p>
<p>Is this something I should use flexbox for? Or is CSS grid suitable to use? </p>
Found a great method on how to control remaining grid items using pseudo-selectors in this article: Control Leftover Grid Items with Pseudo-selectors
CSS Grid is not suitable for alignment across entire rows because crossing rails would get in the way. Here's a detailed explanation:
As an alternative, use flexbox and set
justify-content: center
.This will pack all items in the horizontal center of the row. Your margins will then separate them.
On fully populated rows,
justify-content
will not work because there is no free space for it to work .On rows with free space (in your case, only the last row), the items will appear centered.