我有一个固定的宽度和高度容器,由任意高度元素组成,需要垂直堆叠。如何隐藏任何不适合的元素? overflow: hidden
仍然可以显示不会溢出的元素部分。
.container {
border: 1px solid #eee;
height: 200px;
overflow: hidden;
}
.box {
background-color: #ccc;
line-height: 54px;
margin: 20px;
text-align: center;
width: 60px;
}
.incorrect {
background-color: #fa9;
}

<div class="container">
<div class="box">show</div>
<div class="box">show</div>
<div class="box incorrect">hide</div>
</div>
&#13;
答案 0 :(得分:14)
假设您的子元素与容器具有相同的宽度,可以通过利用从flex
属性创建的包含框来实现。
诀窍是在容器上使用flex-flow: column wrap;
和overflow: hidden;
一起使用。前者规定内容是垂直堆叠的,任何不适合的内容都应该包装在容器内容框之外的第二列中。后者规定应隐藏第二列(以及任何后续列)。
.container {
width: 300px;
height: 200px;
display: flex;
flex-flow: column wrap;
overflow: hidden;
}
.box {
width: 300px;
height: 75px;
}
.box:nth-child(1) {
background: red;
}
.box:nth-child(2) {
background: green;
}
.box:nth-child(3) {
background: blue;
}
&#13;
<div class='container'>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
&#13;
答案 1 :(得分:3)
这样做的一种简单方法是使用CSS columns
而不是flex
。
只需使用等于容器宽度的column-width
即可。在孩子break-inside: avoid
上应用div
。你去吧
它解决了所有要求:
[..]有一个固定的宽度和高度容器,由任意组成 需要垂直堆叠的高度元素。我怎么能隐藏任何 那些不合适的元素?
您可以注意到红色div(最后一个)完全隐藏。
示例代码段
* { box-sizing: border-box; margin: 0; padding: 0; }
.container {
border: 1px solid #999;
height: 200px; width: 300px;
overflow: hidden;
column-width: 300px;
}
.box {
padding: 8px; text-align: center; color: #fff;
width: 250px; height: 80px;
break-inside: avoid
}
.box:nth-child(1) { background: #3b3; }
.box:nth-child(2) { background: #33b; width: 200px; height: 75px; }
.box:nth-child(3) { background: #b33; }
&#13;
<div class="container">
<div class="box">show</div>
<div class="box">show</div>
<div class="box">hide</div>
</div>
&#13;
注意:截至目前,Firefox仍然是CSS列的问题区域。 break-inside
虽然是documented on MDN,但在Firefox中却出现了问题。该错误仍然存在:https://bugzilla.mozilla.org/show_bug.cgi?id=549114。