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

html - Make container shrink-to-fit child elements as they wrap

I'm trying to figure out how flexbox works (supposed to work?…) for cases like below:

.holder {
  width: 500px;
  background: lightgray;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  flex-wrap: nowrap;
}
.v2 {
  width: 320px;
}
.child {
  display: inline-block;
  border: 1px solid black;
  padding: 30px 0px;
  text-align: center;
}
<div class="holder">
  <div class="child">At a glance</div>
  <div class="child">After coverage ends</div>
  <div class="child">Forms &amp; documents</div>
</div>
<br>
<br>
<div class="holder v2">
  <div class="child">At a glance</div>
  <div class="child">After coverage ends</div>
  <div class="child">Forms &amp; documents</div>
</div>
<br>
<br>
<div class="holder v2">
  <div class="child">At a
    <br>glance</div>
  <div class="child">After coverage
    <br>ends</div>
  <div class="child">Forms &amp;
    <br>documents</div>
</div>
question from:https://stackoverflow.com/questions/65924401/how-to-remove-extra-space-between-side-by-side-elements-when-the-right-element-i

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

1 Answer

0 votes
by (71.8m points)

In CSS, the parent container doesn't know when its children wrap. Hence, it continues scaling its size oblivious to what's going on inside.

Put another way, the browser renders the container on the initial cascade. It doesn't reflow the document when a child wraps.

That's why the container doesn't shrink-wrap the narrower layout. It just continues on as if nothing wrapped, as evidenced by the reserved space on the right.

The maximum length of the horizontal white space is the length of the element(s) that the container was expecting to be there.

In the following demo, whitespace can be seen coming and going as the window is re-sized horizontally: DEMO

You'll need a JavaScript solution (see here and here)... or CSS media queries (see here).

When dealing with wrapping text, text-align: right on the container may be helpful in some cases.


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

...