在这个简化的例子中,我有一个书架,书架放在书架上.书架是具有定义宽度的最外层元素.书架上的书应该从左到右显示而不包装.书架应该伸展它的宽度,以展示其架子上的所有书籍.所有书架都需要宽度相同,宽度最宽的书架.
我的HTML:
<div class="bookcase">
<div class="bookshelf">
<div class="book">
<div class="book">
<div class="book">
</div>
<div class="bookshelf">
<div class="book">
<div class="book">
<div class="book">
<div class="book">
</div>
<div class="bookshelf">
<div class="book">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我的CSS:
.bookcase {
width: 40%;
height: 300px;
margin: 0 auto;
background: lightgrey;
overflow-x: auto;
}
.bookshelf {
background: lightgreen;
white-space: nowrap;
}
.book {
display: inline-block;
height: 60px;
width: 60px;
background: pink;
}
Run Code Online (Sandbox Code Playgroud)
当前代码的问题在于,当书架宽度小于最长的书架并且书架使溢出可滚动时,书架元素不会伸展以适合所有书籍.目前,货架似乎将其宽度定义为等于父书柜.
这些图片说明了这个问题.这就是书柜看起来正常的情况,这很好:
要么

但是当书柜缩小时向右滚动时,书架的绿色背景被切断,而不是到达最后一本红皮书的右侧:

如何让书架取出溢出元素的整个宽度,而不是书架父容器的宽度?
感谢 Javalsu、Hashem Qolami 和 Danield 帮助我找到合适的解决方案。事实上,诀窍是利用表格的固有显示属性。我找到的解决方案是将 包装.bookcase在另一个元素中(我将此包装元素称为.wall)。将overflow: auto;带有静态height:和width:属性的移动.bookcase到.wall,然后添加display: table;和width: 100%;到.bookcase。
display: table;当溢出滚动时需要该属性,当溢出不滚动时需要该属性width: 100%;。
我的新 HTML:
<div class="wall">
<div class="bookcase">
<div class="bookshelf">
<div class="book"></div>
<div class="book"></div>
<div class="book"></div>
</div>
<div class="bookshelf">
<div class="book"></div>
<div class="book"></div>
<div class="book"></div>
<div class="book"></div>
</div>
<div class="bookshelf">
<div class="book"></div>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我的新 CSS:
.wall {
width: 60%;
height: 300px;
margin: 0 auto;
background: lightgrey;
overflow: auto;
}
.bookcase {
display: table;
width: 100%;
}
.bookshelf {
background: lightgreen;
white-space: nowrap;
}
.book {
display: inline-block;
height: 60px;
width: 60px;
background: pink;
}
Run Code Online (Sandbox Code Playgroud)
结果:
或者
