JSFiddle - React, Tailwind, and code Playground
HTML
<section>
<ul class="tabsContainer">
<li class="tab">5OFFFRIDAY</li>
<li class="tab">10OFFSUMMER</li>
<li class="tab">SAVEMORE</li>
<li class="tab">HALFOFFEVERYTHING</li>
</ul>
</section>
SCSS
body {
background: #ccc;
}
section {
text-align: center;
width: 375px;
background: white;
margin: 0 auto;
padding: 16px;
position: relative;
display: flex;
overflow: hidden;
}
.tabsContainer {
display: flex;
position: relative;
margin: 0;
padding: 0;
list-style: none;
gap: 0 16px;
transition: left 0.2s ease;
.tab {
border-radius: 25px;
background: gray;
text-align: center;
height: 34px;
display: inline-flex;
align-items: center;
padding: 0 16px;
}
}
JavaScript
window.onload = function(){
const tabsContainer = document.querySelector('.tabsContainer');
const tabs = tabsContainer.querySelectorAll('.tab');
function animate(target) {
let siblings = [];
let elm = target;
let keyframes = [];
let offset;
// Push the widths of each previous element to an array
while (elm = elm.previousElementSibling) {
siblings.push(elm.offsetWidth);
}
// Add the sum of all previous elements
offset = siblings.reduce((prev, current) => prev + current, 0);
// Animate the container to the left
setTimeout(function() {
tabsContainer.style.left = `calc(50% - ${offset}px)`;
}, i * 800);
}
// Run the code
for (i = 0; i < tabs.length; i++) {
animate(tabs[i]);
}
}