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
307 views
in Technique[技术] by (71.8m points)

html - Equal space between flex items

Is there a way to put a full unit of space on both sides of all items, including the first and last?

I am trying to find a way to have equal spacing around flexbox children.

In this article it seems like the nearest thing is justify-content: space-around. It says that:

space-around: items are evenly distributed in the line with equal space around them. Note that visually the spaces aren't equal, since all the items have equal space on both sides. The first item will have one unit of space against the container edge, but two units of space between the next item because that next item has its own spacing that applies.

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

There are at least two methods for equal space between all items, including the first and last items. One method, however, doesn't yet have full browser support.


pseudo-elements

Note this section from Firefox documentation:

In-flow ::after and ::before pseudo-elements are now flex items.

In fact, all major browsers consider pseudo-elements on a flex container to be flex items.

Knowing that, add ::before and ::after to your container.

With justify-content: space-between and zero-width pseudo-elements, the visible flex items will appear evenly spaced.

flex-container {
  display: flex;
  justify-content: space-between;
}

flex-container::before {
  content: "";
}

flex-container::after {
  content: "";
}

/* non-essential decorative styles */
flex-container {
  padding: 5px 0;
  background-color: lightyellow;
  border: 1px solid #aaa;
}
flex-item {
  height: 50px;
  width: 75px;
  background-color: lightgreen;
}
<flex-container>
  <flex-item></flex-item>
  <flex-item></flex-item>
  <flex-item></flex-item>
  <flex-item></flex-item>
</flex-container>

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

...