如果您将 max-width
和 display:inline-block;
应用于包含文本的 div,则该 div 将仅扩展到文本的宽度, 直到文本太宽以至于必须开始新的一行。过了这一点,div 将采用允许的最大宽度,无论最宽的文本行实际有多宽。
我的观点在这个 fiddle 中得到了说明:
https://jsfiddle.net/nx570uu6/
<div class="wrapper">
<div class="item">
words
</div>
<div class="item">
wordswordswords wordswordswords wordswordswords
</div>
<div class="item">
words
</div>
</div>
.wrapper {
width:200px;
height:400px;
background:blue;
}
.item {
max-width:90%;
background:green;
margin:5px 0;
display:inline-block;
}
有没有办法让 div 只和最宽的文本行一样宽?
所以不是这个:
|wordswordswords |
|wordswordswordswords |
|wordswords |
div 看起来像这样:
|wordswordswords |
|wordswordswordswords|
|wordswords |
最佳答案
Flexbox 可以做到 equal height columns并且,按照此处的要求,等宽行。试试这个:
body {
display: flex; /* make .wrapper only as wide as longest content */
}
.wrapper {
display: flex;
flex-direction: column; /* stack flex items vertically */
/* width: 200px; */
height: 400px;
/* background: blue; */
}
.item {
/* max-width: 90%; */
background: chartreuse; /* adjusted color; easier to see text */
margin: 5px 0;
/* display: inline-block; */
}
注意事项:
现在所有
.item
div 的宽度都相等。最长的 div 设置所有的宽度。为了使此方法起作用,您需要删除所有指定的宽度,因为它们会覆盖 flex
align-items: stretch
规则,创建等宽行。如果您希望行的最大宽度为父行的 90%,而不是子行的
max-width: 90%
,请尝试padding-right:父级 10%
。
关于html - 如何将 max-width 应用于文本 div,但让 div 只扩展到它必须扩展的程度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35531174/