小编典典

内联块元素换行时,父包装器不适合新宽度的CSS

html

inline-block如果内容因屏幕宽度而断线,如何获取适合其内容宽度的元素?

<!-- 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>

我想不出如何表达这个问题,听起来似乎很简单,但是我整理了一个简单的插图。

#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>

阅读 360

收藏
2020-05-10

共1个答案

小编典典

你不能 默认情况下,inline-block元素具有缩小到适合的宽度:

收缩至配合宽度为:
min(max(preferred minimum width, available width), preferred width)

然后,

  • 当为时preferred minimum width <= preferred width <= available width,宽度将为preferred width您所希望的。
  • 当为时available width <= preferred minimum width <= preferred width,宽度将为preferred minimum width您所希望的。
  • preferred minimum width <= available width <= preferred width,宽度将是available width,即使你不喜欢它。

如果您确实不希望这样做,我想您可以resize使用JS 添加事件侦听器,然后手动设置所需的宽度。

2020-05-10