问题
有一个内联容器,其中有 2 个垂直堆叠的子容器。如下图:
顶部的绿色子项应将其宽度缩小到底部橙色子项的宽度,将文本包裹在自身内部。所需的布局如下图所示:
问题:单靠CSS怎么办?
其他情况
橙色容器比绿色容器宽(下图)。绿色保持其自然的最大宽度。请注意,即使解决方案会将绿框拉伸(stretch)到 100%,通过为绿框添加一个额外的容器然后将绿框置于其中居中,实现目标解决方案也很容易。
橙色框比父级的最大可能宽度宽(下图)。橙色应该开始包装。注意事项
- 子项的内容是动态的 - 该解决方案需要处理宽度可变的子项。
- 父级是内联的 - 它的宽度不是 100%,而是它最宽的子级的宽度。
- 浏览器支持并不重要。解决方案甚至可以使用 CSS Grid。
代码
fiddle
http://jsfiddle.net/twfky2cr/24/
HTML
<div class="container">
<div class="fitChild">
Some long text that I would like to wrap to fit the container size
set by the orange box
</div>
<div class="fullWidthChild">
This one should set the container size
</div>
</div>
CSS
.container {
display: inline-flex;
flex-direction: column;
flex-wrap: nowrap;
align-items: center;
background-color: black;
}
.container,
.fitChild,
.fullWidthChild {
padding: 10px;
}
.fitChild {
color: white;
background-color: green;;
}
.fullWidthChild {
margin-top: 10px;
background-color: orange;
}
最佳答案
我为您提供了部分解决方案。
http://jsfiddle.net/twfky2cr/166/
我正在为单元格使用 display: table
和 width:1px
。
<div class="table">
<div class="row">
<span class="cell wrap">
Some long text that I would like to wrap to fit the container size
</span>
</div>
<div class="row">
<span class="cell nowrap">
This one should set the container size
</span>
</div>
</div>
.table {
background-color: Black;
display: table;
padding: 1rem;
}
.row {
display: table-row;
}
.cell {
padding: 1rem;
display: table-cell;
width: 1px;
}
.wrap {
color: white;
background-color: Green;
white-space: wrap;
}
.nowrap {
background-color: Orange;
white-space: nowrap;
}
关于html - 如何使其中一个垂直对齐的 child 缩小到其他 child 设置的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51499219/