Maciek Semik Maciek Semik - 6 months ago 15
HTML Question

Using flex-basis to control the number of items displayed on the line

I want to push elements out in order to hide them while using flex.

For example, if

flex-basis
is 50%, show only two items flexed into the given space while the other elements are in
overflow:hidden;
territory.

Or if
flex-basis
is 25% then only show 4 flex elements and hide the others.

Is this possible?



.bargraph {
display: flex;
overflow: hidden;
background: red;
}
.bargraph>dt {
flex-basis: 50%;
}

<dl class="bargraph">
<dt>test</dt>
<dt>test</dt>
<dt>test</dt>
<dt>test</dt>
<dt>test</dt>
<dt>test</dt>
</dl>





https://jsfiddle.net/sffo02dp/

Answer

In addition to flex-basis, use the flex-grow and flex-shrink properties to control sizing.

More specifically:

  • flex-grow: 0
  • flex-shrink: 0
  • flex-basis: 50% (or whatever you want it to be)

This tells flex items: don't grow, don't shrink, be a fixed percentage width

You can combine all these properties into one rule with the flex shorthand property:

flex: 0 0 50%;       /* two items will show, OR... */
flex: 0 0 25%        /* four items will show, OR... */
flex: 0 0 20%        /* five items will show */

Here's the full code:

.bargraph {
  display: flex;
  overflow: hidden;
  background: red;
}
.bargraph>dt {
  flex: 0 0 50%;
}
<dl class="bargraph">
  <dt>test</dt>
  <dt>test</dt>
  <dt>test</dt>
  <dt>test</dt>
  <dt>test</dt>
  <dt>test</dt>
</dl>

Revised Fiddle

Comments