Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - Center flex items on wrap

I have set up a flexbox with two items which should be on the left and right on a normal screen.

If the screen is not big enough to show both next to each other, it should wrap but then they should be centered and not aligned on the left.

I tried different solutions (like using margin: auto on the child items) but that aligned them more to the center even when in the same row.

Here is a simplified example:

.container {
  display: flex;
  align-items: flex-end;
  flex-wrap: wrap;
  justify-content: space-between;
  border: 1px solid black;
  margin-bottom: 25px;
}
.large {
  width: 500px;
}
.small {
  width: 175px;
}
.item {
  width: 100px;
  height: 100px;
  background-color: blue;
  margin: 25px 0px;
}
<div class="container large">
  <div class="item"></div>
  <div class="item"></div>
</div>

<div class="container small">
  <div class="item"></div>
  <div class="item"></div>
</div>
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This may not work in your case, but it's worth mentioning this lesser-known difference between justify-content: space-between and justify-content: space-around.

From the flexbox specification:

8.2. Axis Alignment: the justify-content property

The justify-content property aligns flex items along the main axis of the current line of the flex container.

There are five values that apply to justify-content. Here are two of them:

space-between

Flex items are evenly distributed in the line.

If the leftover free-space is negative or there is only a single flex item on the line, this value is identical to flex-start.

This explains why your items align left on wrap with space-between.

Now look at space-around:

space-around

Flex items are evenly distributed in the line, with half-size spaces on either end.

If the leftover free-space is negative or there is only a single flex item on the line, this value is identical to center.

Hence, to center-align flex items on wrap, consider using space-around.

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around; /* ADJUSTMENT */
  border: 1px solid black;
}
.item {
  width: 200px;
  height: 100px;
  background-color: blue;
  margin: 25px;
}
<div class="container">
    <div class="item"></div>
    <div class="item"></div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...