I have an element (container) with horizontal scroll. For example:
<div class="rows">
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="row">
<div id="container"></div>
</div>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
</div>
If you move the element to another row, it will reset the horizontal scroll in the container. Why is that? How can I maintain the scroll position? Is it possible to fix with only CSS?
Here’s a demo:
https://jsbin.com/gugotewane/2/edit?html,css,js,output
2
Answers
A trick can do. you can preserve the scroll position before moving it to another row.
In your JSBin snippet, you are manipulating the DOM with Javascript by removing one row and then appending it to the row below. This forces the browser to re-render the page and reset the scrollbars.
To solve this problem (again in Javascript), you need to get the horizontal scroll position before manipulating the DOM with:
and then reapply the horizontal scroll after appending the row again with:
where
container
is your containerdiv
element.The reason for the scrollbars (both horizontal and vertical scrollbars) resetting is that browsers re-render the page after the DOM is manipulated and by default the browsers do not remember the scrollbar positions.
There is an interesting CSS property that you may be interested in looking at, namely:
overflow-anchor
which would appear to maintain the scrollbar positions after rendering.However, after reading CSS Scroll Anchoring, CSSWG, expecially Scroll Adjustment, it would appear that scroll anchoring only applies to vertical scrolling.
So, I would guess that this is not possible only with CSS.