问题
I have a CSS grid with 3 rows. There may be less than 3 items to fill it, and I want to start filling it from the bottom.
I've created a jsFiddle for you to play with, but it currently fails to do what I want.
html, body, div {
height: 100%;
}
div {
display: grid;
grid-template-columns: 1;
grid-template-rows: repeat(3, 1fr);
/* MISSING RULE */
}
<div>
<p>Last item</p>
<p>Second last item</p>
<p>Top item</p>
</div>
Actual output:
Last item
Second last item
Top item
Desired output:
Top item
Second last item
Last item
I'd like to apply one rule to the <div>
that contains the grid, rather than separate rules to the items in the grid, if that is possible.
回答1:
There is no column-reverse function in CSS Grid, like there is in flexbox.
Therefore, getting grid areas to populate a container starting from the bottom isn't possible with a single rule in the container.
Here's how it would work in flexbox:
div {
display: flex;
flex-direction: column-reverse;
height: 100vh;
}
p {
flex: 1;
}
/* demo styles */
p {
margin: 0;
background-color: lightgreen;
}
p + p {
margin-bottom: 10px;
}
body {
margin: 0;
}
<div>
<p>Last item</p>
<p>Second last item</p>
<p>Top item</p>
</div>
回答2:
If you want to use CSS Grid layout it will be like this. I modify your HTML. You have to write CSS property for grid child item where to start and where to end. grid-row-start:
and grid-row-end:
. Here is a CodePen.
.grid-item{
border: 2px solid red;
border-radius: 5px;
height: 200px;
padding: 10px;
width: 300px;
margin-left: auto;
margin-right: auto;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: repeat(3, 1fr);
}
.grid-item p{
margin: 0;
}
.grid-item .first-item{
grid-row-start: 1;
}
.grid-item .last-item{
grid-row-start: 3;
}
<div class="grid-item">
<p class="last-item">Last item</p>
<p class="second-item">Second last item</p>
<p class="first-item">Top item</p>
</div>
If you want to use flexbox
it will be using two line code.
<div>
<p>Last item</p>
<p>Second last item</p>
<p>Top item</p>
</div>
CSS for this
div{
display: flex;
flex-direction: column-reverse;
}
The flex-direction CSS property sets how flex items are placed in the flex container defining the main axis and the direction (normal or reversed).
来源:https://stackoverflow.com/questions/61012385/filling-cells-starting-from-the-bottom-in-css-grid