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

html - CSS when inline-block elements line-break, parent wrapper does not fit new width

How do you get an inline-block element to fit its content width, if the content line-breaks because of screen width?

<!-- parent inline-block -->
<div style='display: inline-block;'>
    <div style='display: inline-block; width:200px;'></div>
    <!--
        If this child line breaks, 
        two 200px wide blocks are stacked vertically.
        That should make the parent width 200px,
        but the parent stays much wider than that
    -->
    <div style='display: inline-block; width:200px;'></div>
</div>

I can't think of how to phrase the question so it sounds easy, but I put together a simple JSFiddle illustrating.

#wide {
  position: relative;
  width: 100%;
  border: 1px solid black;
  padding: 5px;
}
#narrow {
  position: relative;
  width: 175px;
  border: 1px solid black;
  padding: 5px;
}
.wrap {
  display: inline-block;
  border: 1px solid green;
  margin: auto;
}
.inlineblock {
  display: inline-block;
  vertical-align: top;
  background: red;
  min-width: 100px;
  min-height: 100px;
  border: 1px solid black;
}
<section id='wide'>
  <div class='wrap'>
    <div class='inlineblock'></div>
    <div class='inlineblock'></div>
  </div>
</section>
<p>
  When the red inline-blocks are forced to line break, how do you make a parent with display:inline-block (the green border) snap to fit? How do you get rid of all the extra horiztonal space in the lower green bordered div?
</p>
<section id='narrow'>
  <div class='wrap'>
    <div class='inlineblock'></div>
    <div class='inlineblock'></div>
  </div>
</section>
Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

You can't. By default, inline-block elements have a shrink-to-fit width:

The shrink-to-fit width is:
min(max(preferred minimum width, available width), preferred width).

Then,

  • When preferred minimum width <= preferred width <= available width, the width will be the preferred width, as you desire.
  • When available width <= preferred minimum width <= preferred width, the width will be the preferred minimum width, as you desire.
  • When preferred minimum width <= available width <= preferred width, the width will be the available width, even if you don't like it.

If you really don't want this, I guess you could add a resize event listener with JS, and set the desired width manually.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...