自动边距能否像在Flexbox中一样在CSS Grid中工作? [英] Can auto margins work in CSS Grid like they do in Flexbox?

查看:94
本文介绍了自动边距能否像在Flexbox中一样在CSS Grid中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,flexbox可以做的任何事情,css-grid也应该可以做(通常更为冗长).

As far as I understand, anything flexbox can do, css-grid should also be able to do (usually more verbosely).

但是我还不知道如何用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 lis 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆