Should you be comfortable with setting the wrapper's height statically to match the highest item (otherwise, continue reading), you can enable wrapping for items by eliminating white-space: nowrap
and introducing overflow-y: hidden;
(alongside height
):
.wrapper {
border: 1px solid black;
display: block;
overflow-x: hidden;
overflow-y: hidden; /* <=== */
height: 64px; /* <=== */
width: 200px;
}
Live Demonstration:
.wrapper {
border: 1px solid black;
display: block;
overflow-x: hidden;
overflow-y: hidden; /* <=== */
height: 64px; /* <=== */
width: 200px;
}
.item {
border: 1px solid red;
box-sizing: border-box;
display: inline-block;
*display:inline; /* for IE7*/
*zoom:1;/* for IE7*/
width: 40%;
}
.hidden {
display: none;
}
#i1{ height: 32px; }
#i2{ height: 64px; }
#i3{ height: 48px; }
<div class="wrapper">
<div id="i1" class="item">
item 1
</div>
<div id="i2" class="item">
item 2
</div>
<div id="i3" class="item">
item 3
</div>
</div>
This approach functions because the child elements are displayed as inline-block
, and when the last child wraps, it becomes hidden due to insufficient parent height.
If the above method is not suitable, an alternative using JavaScript might be necessary:
const wrapper = document.querySelector(".wrapper");
const wrapperBox = wrapper.getBoundingClientRect();
for (const child of wrapper.children) {
const childBox = child.getBoundingClientRect();
child.classList.toggle("hidden", overflows(wrapperBox, childBox));
}
function overflows(parentBox, childBox) {
return childBox.right > wrapperBox.right ||
childBox.bottom > wrapperBox.bottom ||
childBox.left < wrapperBox.left ||
childBox.top < wrapperBox.top;
}
It would require periodic execution upon layout changes, unlike CSS where the browser handles it automatically.
Live Demonstration:
const wrapper = document.querySelector(".wrapper");
const wrapperBox = wrapper.getBoundingClientRect();
for (const child of wrapper.children) {
const childBox = child.getBoundingClientRect();
child.classList.toggle("hidden", overflows(wrapperBox, childBox));
}
function overflows(parentBox, childBox) {
return childBox.right > wrapperBox.right ||
childBox.bottom > wrapperBox.bottom ||
childBox.left < wrapperBox.left ||
childBox.top < wrapperBox.top;
}
.wrapper {
border: 1px solid black;
display: block;
overflow-x: hidden;
white-space: nowrap;
width: 200px;
}
.item {
border: 1px solid red;
box-sizing: border-box;
display: inline-block;
*display:inline; /* for IE7*/
*zoom:1;/* for IE7*/
width: 40%;
}
.hidden {
display: none;
}
#i1{ height: 32px; }
#i2{ height: 64px; }
#i3{ height: 48px; }
<div class="wrapper">
<div id="i1" class="item">
item 1
</div>
<div id="i2" class="item">
item 2
</div>
<div id="i3" class="item">
item 3
</div>
</div>