Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

html - Can auto margins work in CSS Grid like they do in Flexbox?

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

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Generally speaking, for alignment in flexbox there are two levels to manage:

  1. the flex container, and
  2. the flex items.

In CSS Grid, there are three levels to manage:

  1. the grid container,
  2. the rows / columns ("tracks"), and
  3. the grid items (which exist inside tracks).

When you set an auto margin on a flex item, it consumes space in the container. That's enough to space an item away from its siblings. You're done.

When you set an auto margin on a grid item, it consumes space in the track (not the container). So your tracks are not affected by auto margins.

You can see this in your Grid example. The item with margin-top: auto is pinned to the bottom of the track. While in the Flex example it's pinned to the bottom of the container.

There is no apples-to-apples method for Grid to emulate this flexbox behavior because, as mentioned above, in one case you have a container-item relationship, and in the other case you have a container-track-item relationship.

Put another way, since you're dealing with items that are all in the same line in flexbox, the spacing between them is easy. Since you're dealing with items that exist in different lines in Grid, there's more complexity.

You would need to apply the auto margin to the grid row, not the item, for it to behave like flexbox. Or, you would need to target and expand the particular grid-row-gap. None of these methods exist. The spec doesn't provide for auto margins on grid tracks or for multiple values on grid gaps in the same axis.

CSS Grid isn't here to replace flexbox. It's not even meant to be an enhanced version. Therefore, expect to find cases where flex is more useful than Grid. This post is a case in point.

Here are two other examples where flexbox may have the advantage:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...