自动边距可以像在 Flexbox 中那样在 CSS Grid 中工作吗? [英] Can auto margins work in CSS Grid like they do in Flexbox?
问题描述
据我所知,flexbox 可以做的任何事情,css-grid 也应该可以做(通常更冗长).
As far as I understand, anything flexbox can do, css-grid should also be able to do (usually more verbosely).
然而,我不知道如何模仿一个 flexbox,其中一个项目用 margin: auto
Yet I cannot figure out how to mimic a flexbox with an item pushing off the others with margin: auto
ul {
list-style-type: none;
padding: 0;
display: flex;
flex-direction: column;
outline: 1px solid red;
height: 200px;
background-color: lime;
}
li {
background-color: cornsilk;
}
li:last-of-type {
margin-top: auto;
}
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
看看所有单元格是如何根据其内容调整大小的,最后一个 li
是如何将其他单元格推开以显示在最后?
See how all cells are sized to their content and the last li
pushes the others away to appear at the end?
如何在不修改 html 以添加元素的情况下使用 css-grid 执行此操作?
How would I do this with css-grid without modifying my html to add element?
ul {
list-style-type: none;
padding: 0;
display: grid;
outline: 1px solid red;
height: 200px;
background-color: lime;
}
li {
background-color: cornsilk;
}
li:last-of-type {
margin-top: auto;
}
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
这很接近,但所有行的大小都不是 min-content
- 我不知道它们的大小是什么,但它不是 min-content
.我能得到的最接近的是添加
This is close, but all rows are not sized to min-content
- I have no idea what they are sized to but its not min-content
. The closest I can get is to add
grid-template-rows: repeat(3, min-content);
这是可行的,但前提是您提前知道 li
的数量,这对于 flexbox 版本来说是不必要的.
which works but only if you know the amount of li
s ahead of time which is not necessary for the flexbox version.
推荐答案
有一种方法可以获取您的请求,虽然可能有点粗鲁,但很有效.
There is a way to get your request, that can be considered a little bit hackish, but that is effective.
在所有列表元素和最后一个元素之间创建任意数量的未使用行.这里有一个片段,只要列表的元素少于 99 个:
Create an arbitrary number of unused rows between all the list elements and the last one. Here a snippet that will work as far as the list has less than 99 elements:
ul {
list-style-type: none;
padding: 0;
display: grid;
outline: 1px solid red;
height: 150px;
background-color: lime;
grid-template-rows: repeat(99, max-content) 1fr [last];
}
li {
background-color: cornsilk;
}
li:last-of-type {
grid-row: last;
}
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
这篇关于自动边距可以像在 Flexbox 中那样在 CSS Grid 中工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!