3

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

djvg
  • 11,722
  • 5
  • 72
  • 103

2 Answers2

2

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>
djvg
  • 11,722
  • 5
  • 72
  • 103
Pedro Figueiredo
  • 2,304
  • 1
  • 11
  • 18
1

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>
djvg
  • 11,722
  • 5
  • 72
  • 103
Temani Afif
  • 245,468
  • 26
  • 309
  • 415