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

标签 html css

如果内容因屏幕宽度而换行,如何让 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>

我想不出如何表达这个问题,所以听起来很简单,但我整理了一个简单的 JSFiddle 说明。

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

最佳答案

你不能。默认情况下,inline-block元素有一个 shrink-to-fit width :

The shrink-to-fit width is:
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 事件监听器,并手动设置所需的宽度。

关于html - 内联 block 元素换行时的CSS,父包装器不适合新宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55954720/

相关文章:

html - 整个 Controller 在函数调用中被调用

html - 基于 Table/Table-cell 的 3 列布局在 Chrome 和 Opera 上不起作用

html - 裁剪出css图片容器

html - 为什么 float 父级中的空 span 标记会在新行上呈现?

html - 父级和第一个/最后一个子级的边距折叠如何工作?

html - 如何在 Flexbox 对齐的侧边栏上模拟 'position:fixed' 行为

javascript - 获取数据 MySQL DB 并在 HTML 中显示

html - CSS将元素移动到顶部而不使用负值

javascript - 在 Jquery 中选择仅具有类 "doc-count"的 anchor

javascript - JavaScript 中矩阵的算法建议