user10642279
user10642279

Reputation:

Hide entire child div when overflow occur in parent div

I have 5 child div inside a fixed parent div whose height varies based on device. I'm looking for any hack to hide the entire div if it cannot fit in the fixed parent div.

I've tried "overflow: hidden;" but it only crops the part that is overflowing and not the entire div

.fixed-div {
  background: greenyellow;
  height: calc(100vh - 10px);
  width: 100px;
  position: fixed;
  overflow: hidden;
}

.child-div {
  width: 60px;
  height: 60px;
  background: red;
  margin: 20px auto;
}
<div class="container">
  <div class="fixed-div">
    <div class="child-div"></div>
    <div class="child-div"></div>
    <div class="child-div"></div>
    <div class="child-div"></div>
    <div class="child-div"></div>
    <div class="child-div"></div>
    <div class="child-div"></div>
  </div>
</div>

Expected: If the height can accomudate only 2 child div then other 5 child div should not be displayed or cropped completely

Upvotes: 3

Views: 2494

Answers (2)

Temani Afif
Temani Afif

Reputation: 272901

Use flexbox and a colmun direction then enable the wrap. The elements will automatically move to a new column when there isn't enough space to hold them. Since you also fixed the width the new column will get hidden too.

.fixed-div {
  background: greenyellow;
  height: calc(100vh - 10px);
  width: 100px;
  position: fixed;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

.child-div {
  width: 60px;
  height: 60px;
  background: red;
  margin: 10px 20px;
}

.child-div:first-child {
  margin-top: 20px;
}
<div class="container">
  <div class="fixed-div">
    <div class="child-div"></div>
    <div class="child-div"></div>
    <div class="child-div"></div>
    <div class="child-div"></div>
    <div class="child-div"></div>
    <div class="child-div"></div>
    <div class="child-div"></div>
  </div>
</div>

Upvotes: 1

Pedro Figueiredo
Pedro Figueiredo

Reputation: 2452

This can be done with CSS grid, by defining a max-width and a dynamic number of rows, as well as defining overflow: hidden to hide items that don't have space. Take a look at this:

.fixed-div {
  display: grid;
  grid-template-rows: repeat( auto-fit, minmax(100px, 1fr));
  grid-template-columns: 100px;
  grid-auto-flow: column;
  background: greenyellow;
  max-height: calc(100vh - 10px);
  max-width: 100px;
  overflow: hidden;
}

.child-div {
  width: 60px;
  height: 60px;
  background: red;
  margin: 20px auto;
}
<div class="fixed-div">
  <div class="child-div"></div>
  <div class="child-div"></div>
  <div class="child-div"></div>
  <div class="child-div"></div>
  <div class="child-div"></div>
  <div class="child-div"></div>
  <div class="child-div"></div>
</div>

Upvotes: 2

Related Questions