Brad Brad - 2 months ago 8
CSS Question

Completely hiding block elements that don't fully fit in the visible part of their parent

Suppose I have three block elements in a container. The black line indicates the container. The blue boxes are the three block elements within it.

Elements

These three elements don't quite fit. If I set

overflow: hidden
on the outer element, I will see the top two elements and partially the third.

What I would like, is to only display elements that fully fit within the container.

Elements, corrected

Is this possible with CSS?

Answer

Yes it is possible with Flexbox, you need to set flex-direction: column , flex-wrap: wrap and also overflow: hidden.

Also you need to set full width or calc(100% - margin) on flex-childs so when last elements wraps itself it will go out of parent element and overflow: hidden on parent will take care of rest.

* {
  box-sizing: border-box;
}
.container {
  height: 200px;
  width: 200px;
  border: 1px solid black;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  overflow: hidden;
}
.box {
  flex: 0 0 70px;
  width: calc(100% - 10px);
  margin: 5px;
  background: #46A1FF;
}
<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

Comments