据我所知,任何flexbox都可以做,css-grid也应该能够做到(通常更加冗长)。
然而,我无法弄清楚如何使用margin: auto
推动其他项目来模仿Flexbox
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
将其他细胞推到最后?
如何在不修改我的html添加元素的情况下使用css-grid执行此操作?
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
。我能得到的最接近的是添加
grid-template-rows: repeat(3, min-content);
哪个有效,但前提是你知道li
s的数量,这对于flexbox版本是不必要的。
有一种方法可以获得您的请求,这可以被视为有点hackish,但这是有效的。
在所有列表元素和最后一个列表元素之间创建任意数量的未使用行。这里的代码片段可以在列表中使用少于99个元素:
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中,有三个级别需要管理:
在flex项目上设置auto
边距时,它会占用容器中的空间。这足以让物品远离其兄弟姐妹。你完成了。
在网格项上设置auto
边距时,它会占用轨道(而不是容器)中的空间。所以你的曲目不受auto
边缘的影响。
您可以在Grid示例中看到这一点。带有margin-top: auto
的项目固定在轨道的底部。在Flex示例中,它固定在容器的底部。
Grid没有巧妙的方法来模拟这种flexbox行为,因为如上所述,在一种情况下,您有一个容器 - 项目关系,而在另一种情况下,您有一个容器 - 跟踪 - 项目关系。
换句话说,由于您正在处理Flexbox中同一行中的项目,因此它们之间的间距很容易。由于您处理Grid中不同行中存在的项目,因此复杂性更高。
您需要将auto
边距应用于网格行,而不是项目,因为它的行为类似于flexbox。或者,您需要定位和扩展特定的grid-row-gap
。这些方法都不存在。该规范没有规定网格轨道或auto
上的multiple values on grid gaps in the same axis边距。
CSS Grid不是为了取代flexbox。它甚至不是一个增强版本。因此,期望找到flex比Grid更有用的情况。这篇文章就是一个很好的例子。
以下是另外两个示例,其中flexbox可能具有以下优势:
你需要使用grid-template-rows
,它用于声明每行占用的区域
ul {
list-style-type: none;
padding: 0;
display: grid;
outline: 1px solid red;
height: 200px;
background-color: lime;
grid-template-rows: minmax(1px, auto) minmax(1px, auto) minmax(1px, auto) 1fr;
}
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>
另外需要注意的是,CSS Grid并不能真正取代flexbox的需求。 https://css-tricks.com/css-grid-replace-flexbox/