开发者

Fixing an element to the top

开发者 https://www.devze.com 2023-02-28 15:02 出处:网络
I have an element fixed to the top x, y axis. Is there any way how I change it to be fixed only to the x-axis? E.g. - so I would be able to scroll the fixed element to the left and to the right.

I have an element fixed to the top x, y axis. Is there any way how I change it to be fixed only to the x-axis? E.g. - so I would be able to scroll the fixed element to the left and to the right.

Current code:

<div style="position:fixed;top:0;width:2000px;">
The fixed header element
&l开发者_C百科t;/div>
<div style="overflow:auto;width:2000px;">
the scrollable content element
</div>


This is a terrific question and CSS3 has no answer for you. There's no way to fix an element in one axis but not the other.

The ideal solution, imo, is to offer CSS3 attributes like, say, position:fixed-x and position:fixed-y. But there is no such thing.

The only way I know of to have this very useful behavior is to write JavaScript function to handle a setInterval( ) event; poll the current X or Y scroll position at each event; and, if the scroll position on the axis you want to fix has changed, then change the scroll position of the fixed element to compensate, i.e., to move it back to where it belongs.

I actually use this method and it works, but it's a pain. My code polls the X and Y scroll positions every tenth of a second, which is often enough to not look too herky-jerky.

You can see the solution at work in this long table. Narrow the window to make a horizontal scroll bar appear, the scroll the table left and right. The column heads move with the table but you can scroll the table body vertically and the column heads stay put.

0

精彩评论

暂无评论...
验证码 换一张
取 消