在这个简化的示例中,我有一个书柜,书架上放着书籍。书架是具有定义宽度的最外面的元素。书架上的书应该从左到右排列,没有包装。书架应该拉伸其宽度以显示书架上的所有书籍。所有书架的宽度必须相同,即最宽书架的宽度。
My 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>
My 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;
}
jsFiddle 演示 http://jsfiddle.net/gr9rg/3/
当前代码的问题在于,当书架宽度小于最长的书架并且书架使溢出可滚动时,书架元素不会拉伸以适合所有书籍。目前,书架的宽度似乎等于父书架的宽度。
这些图片很能说明问题。这是书柜正常的样子,很好:
or
但是,当书架较窄时向右滚动时,书架的绿色背景被切断,而不是到达最后一本红色书的右侧:
如何使书架占据溢出元素的整个宽度,而不是书架父容器的宽度?
感谢 Javalsu、Hashem Qolami 和 Danield 帮助我找到了合适的解决方案。事实上,诀窍是利用表格固有的显示属性。我找到的解决方案是将.bookcase
在另一个元素中(我将此包装元素称为.wall
)。移动overflow: auto;
与静电height:
and width:
属性来自.bookcase
to the .wall
,并添加display: table;
and width: 100%;
to the .bookcase
.
The 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>
我的新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;
}
jsFiddle 演示 http://jsfiddle.net/gr9rg/8/
Result:
or
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)