I have a list of items in a container. The container takes the full width of the parent, allowing the items to overflow horizontally if needed. Here's what it looks like:
ul {
list-style: none;
display: flex;
overflow-x: auto;
padding: 0;
margin: 0;
border: 1px dotted black;
}
li {
margin-right: 10px;
}
li:last-child {
margin-right: 0;
}
a {
display: block;
text-decoration: none;
white-space: nowrap;
padding: 4px 8px;
color: black;
background-color: white;
border: 1px solid black;
}
a.active {
background-color: blue;
}
<ul id="container">
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#" class="active" id="element">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
</ul>
In the list of items, there is one that has the .active class. I want to horizontally scroll the container in a way such that this item is exactly centered. To do this, I wrote the following function:
function toMiddle(element, container) {
if (container === undefined) {
container = window;
}
var elementRect = element.getBoundingClientRect();
var absoluteElementLeft = elementRect.left;
var middleDiff = (elementRect.width / 2);
var scrollLeftOfElement = absoluteElementLeft + middleDiff;
var scrollX = (scrollLeftOfElement - (container.getBoundingClientRect().width / 2));
container.scrollTop = 0;
container.scrollLeft = scrollX;
}
And I'm trying to call this to center the container as follows:
toMiddle(document.getElementById("element"), document.getElementById("container"));
Unfortunately, this doesn't seem to work properly. Any idea how I can fix this? And what exactly am I doing wrong here?
Please note, scrollIntoView() works perfectly well, but it scrolls the whole page vertically as well, which is not an acceptable thing for my use case.