- As the container slides to the left, I want each tab to be centered for a brief moment in the container.
- Before the animation begins, I want the very first tab to be centered in the container on page load before the animation begins. I know I need to divide each element's
offsetWidthby 2 so that it is calculated to be centered but I'm not sure where/how to do that.
Link to JS Fiddle: https://jsfiddle.net/nb5a92x3/
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]);
}
}
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;
}
}
<section>
<ul class="tabsContainer">
<li class="tab">TAB ONE</li>
<li class="tab">ANOTHER TAB HERE</li>
<li class="tab">A REALLY LONG TAB HERE</li>
<li class="tab">LAST TAB</li>
</ul>
</section>