Force width of flex item to be 50%

Viewed 4539

I'm trying to create a flex based container where the items should be expanded on hover with an animation. All items should first be of equal width dependent on the total width of the container. When hovering an item, the item hovered should be exactly 50% of the total container width, with the rest of the items not hovered being shrunk to fill the remaining space.

This seems like a very easy thing to do, but I can't really wrap my head around how to achieve the result I'm after.

I've tried this code: https://codepen.io/tobiasger/pen/xxRWxpV

.flex-container {
  width:100%;
  display:flex;
  height:300px;
}

.flex-item {
  flex:1;
  transition: all 0.4s ease;
}

.flex-item:hover {
  flex-basis:50%;
}

But the flex-basis is not resulting in 50% of the container. I'm not sure what it's basing it's percentage on, it seems closer to the window width than the actual container width.

I've also tried applying a min-width value of 50% to the hovered item, but that doesn't seem to be possible to animate.

The goal is to not have to create specific classes for containers depending on how many items they contain. If it's possible to always force the hovered item to be exactly 50% of the container width while having the rest of the items fill the remaining 50% equally, and also animate this width change, I would be very happy!

2 Answers

Just add flex-grow:0; to .flex-item:hover.

.flex-item:hover {
  flex-basis: 50%;
  flex-grow: 0;
}

This works too

.flex-item:hover {
  flex: 0 50%;
}

It works when you use width instead of flex-basis in the following way:

html,
body {
  margin: 0;
}

.flex-container {
  width: 100%;
  display: flex;
  height: 300px;
}

.flex-item {
  flex-grow: 1;
  flex-shrink: 1;
  width: calc(100% / 6);
  transition: all 0.4s ease;
}

.flex-item:nth-child(odd) {
  background: #666;
}

.flex-item:nth-child(odd) {
  background: #333;
}

.flex-item:hover {
  width: 50%;
  flex-shrink: 0;
}
<div class="flex-container">
  <div class="flex-item"></div>
  <div class="flex-item"></div>
  <div class="flex-item"></div>
  <div class="flex-item"></div>
  <div class="flex-item"></div>
  <div class="flex-item"></div>
</div>

Related