There is a block with limited width. It has buttons. The sum of the button widths is wider than the width of the parent. A scroll appears. When you press a button, it should scroll in the direction it needs until it (the pressed button) is in the center of the parent block.
Scrolling seems to work, but the buttons are not centered correctly, apparently due to the fact that the outermost element rests on the scroll border or block border and this prevents further scrolling. It turns out that only the 4th and 5th buttons are in the center, although they are already almost in the center (and to be honest, I’m not sure that they are doing everything right either). The remaining buttons twitch slightly, but do not become centered. Help me solve the problem.
<div class="block">
<button class="button">Button 1</button>
<button class="button">Button 2</button>
<button class="button">Button 3</button>
<button class="button">Button 4</button>
<button class="button">Button 5</button>
<button class="button">Button 6</button>
</div>
.block {
display: flex;
justify-content: center;
align-items: center;
height: 80px;
width: 200px;
border: 1px solid #ccc;
margin-bottom: 20px;
overflow: scroll;
}
text-align: center;
}
.button {
padding: 10px 20px;
margin: 0 5px;
background-color: #f1f1f1;
border: none;
cursor: pointer;
}
.button:hover {
background-color: #ddd;
}
.button.active {
background-color: #007bff;
color: #fff;
}
// Get all the buttons within the container
const buttons = document.querySelectorAll('.button');
// Add event listener to each button
buttons.forEach((button) => {
button.addEventListener('click', () => {
// Remove the "active" class from all buttons
buttons.forEach((btn) => btn.classList.remove('active'));
// Add the "active" class to the clicked button
button.classList.add('active');
// Scroll the container to the center of the clicked button
const container = button.parentElement;
const containerWidth = container.offsetWidth;
const buttonWidth = button.offsetWidth;
const buttonOffset = button.offsetLeft;
const scrollAmount = buttonOffset - (containerWidth / 2) + (buttonWidth / 2);
container.scrollLeft = scrollAmount;
});
});
I am just learning. I haven’t tried much. And I barely wrote this code 🙂