【发布时间】:2016-05-01 22:44:42
【问题描述】:
如果内容因屏幕宽度而换行,如何让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>
【问题讨论】:
-
你不能……这不是线盒模型的工作原理。
-
您可能还想将父 div 宽度设置为 200px?
-
使用 white-space:preline 我可以摆脱额外的宽度空间,但它会强制 inline-block 元素从一开始就换行。没有办法只在换行时做前置空白吗?
-
我认为你应该搜索 CSS Flex 它可能是你需要的......
-
@miguelmpn 不……连 flexbox 都做不到。