Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide an element if it does not fit in a flex layout?

I'm trying to make a horizontal flexbox div that has 3 items. Each has a min-width, and I want to hide them as the screen gets too small to fit them. If I knew the width of all 3 divs, I would just use media queries to hide the divs at the right breakpoints. The problem is that div1 is an image with dynamic width (recreated in example with random width)

Is there any way to hide an element if it doesn't fit into the flexbox container?

Its kind of hard to explain but hopefully running this code snippet a few times will show what I'm after:

let width = (Math.random()*600)
document.getElementById('one').style.minWidth = width + 'px'
.root {
  display: flex;
  justify-content: space-between;
}

.one {
  background-color: red;
}

.two {
  min-width: 200px;
  background-color: green;
}

.three {
  min-width: 300px;
  background-color: yellow;
  flex: 1
}
<div class="root">
  <div id="one" class="one">
    unknown width
  </div>
  <div class="two">
    hide me if im off the screen
  </div>
  <div class="three">
    hide me if im off the screen
  </div>
</div>
like image 708
Egor Egorov Avatar asked Jul 25 '18 19:07

Egor Egorov


1 Answers

Since you have a fixed height image, you can set root to a maximum height and use flex-wrap: wrap.

let width = (Math.random()*600)
document.getElementById('one').style.minWidth = width + 'px'
.root {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  overflow:hidden;
  max-height:50px;
  overflow-y:hidden;
}

.one {
  background-color: red;
  height: 50px;
}

.two {
  min-width: 200px;
  background-color: green;
}

.three {
  min-width: 300px;
  background-color: yellow;
  flex: 1
}
<div class="root">
  <div id="one" class="one">
    unknown width
  </div>
  <div class="two">
    hide me if im off the screen
  </div>
  <div class="three">
    hide me if im off the screen
  </div>
</div>

http://jsfiddle.net/4y39h8jn/1/

like image 159
Luke Bordonaro Avatar answered Oct 29 '22 11:10

Luke Bordonaro