Flexbox individual items not centred
01:10 06 Jun 2026

I have an animated flexbox whereby any item you're pointing at gets more space. This does happen, except the item only gets space to its right rather than on both sides. Also, the flex-grow ratio is 2:1 but the pointed item seems to be getting a lot more. Adding justify-content: center has no effect on the issue. Can anyone help me understand what drives this behaviour? Screenshots and code below, first image is appearance on load, second image is when hovering over the third item. Excuse the janky graphics I'm just trying to get it to work:



  
    
  
  
    
    
Not A Noob

Stuff I Did

body {
  margin: 0;
  font-family: sans-serif;
}

main > section {
    display: block;
}

.main-swiper__wrapper {
  height: 300px;
}

.main-swiper__flex {
  display: flex;
  height: 100%;
  background: dodgerblue;
  padding: 0;
  margin: 0;
  list-style: none;
}

.main-swiper__item {
  flex: 0;
  height: 100%;
  transition: flex 0.3s ease;
}

.main-swiper__item img {
  height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
}
console.log("JS loaded");

const flexContainer = document.querySelector(".main-swiper__flex");
const items = document.getElementsByClassName("main-swiper__item");

console.log("container: " + JSON.stringify(flexContainer.style.flex));

flexContainer.addEventListener("mouseleave", containerShrink);
//flex.addEventListener("mouseleave", outShrink);
for (let i = 0; i < items.length; i++) {
  items[i].addEventListener("mouseenter", expand);
  items[i].addEventListener("mouseleave", shrink);
}

function expand(e) {
  for (let i = 0; i < items.length; i++) {
    if (items[i] !== e.currentTarget) {
      items[i].style.flex = "1 0 5%";
    }
  }
  e.currentTarget.style.flex = "2 0 5%";
  //e.currentTarget.querySelector("img").style.transform = "scale(1.2)";
}

function shrink(e) {
  e.currentTarget.style.flex = "1 0 5%";
  //e.currentTarget.querySelector("img").style.transform = "scale(1)";
}

function containerShrink() {
  for (let i = 0; i < items.length; i++) {
  items[i].style.flex = 0;
  }
}

Appearance on load

Appearance when hovering on an item (third from the left)

css flexbox