flexbox resize child width should change only next sibling width

Viewed 217

I have a flexbox container that has dynamic number of items.

All the items should fill the container's width. The items width should be relative to the container width, not in px units.

I want to be able to resize each time one item (except for the last one), and it should change only the width of itself and its right sibling item. For example, if I have 4 items, initially each item width should be 25%, and if I drag item1 to be smaller, its width should decrease to 20%, item2 should grow to 30%, and the rest of the items should stay the same width of 25%.

here is my progress so far:

.container {
  display: flex;
}

.item {
  width: 25%;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #4fa0f38c;
  border: 1px solid white;
}

.item:not(:last-child) {
  resize: horizontal;
  overflow: auto;
}
<div class='container'>
  <div class='item'>item 1</div>
  <div class='item'>item 2</div>
  <div class='item'>item 3</div>
  <div class='item'>item 4</div>
</div>

I'm looking for a solution using css with flex (no js).

1 Answers

You can rely on the active state to simulate this but it's not very accurate because :active will trigger with any click event:

.container {
  display: flex;
}

.item {
  width: 25%;
  height: 60px;
  display: flex;
  flex-grow:1;
  align-items: center;
  justify-content: center;
  background-color: #4fa0f38c;
  border: 1px solid white;
}

.item:not(:last-child) {
  resize: horizontal;
  overflow: auto;
}
/* all the element should not shrink */
.container:active *{
  flex-shrink:0;
}
/* allow only the right element to shrink*/
.item:active + * {
  flex-shrink:1;
}
/* make the right element grow more (when we decrease the left one)*/
.item:active + * {
  flex-grow:99999;
}
<div class='container'>
  <div class='item'>item 1</div>
  <div class='item'>item 2</div>
  <div class='item'>item 3</div>
  <div class='item'>item 4</div>
</div>

Related