简体   繁体   中英

CSS how to fix an element to scroll horizontally with the page but not vertically?

I have created an example to help explain. http://jsfiddle.net/9AUbj/1/

<style>
div#one {}
div#two {
    height: 50px;
    background-color: blue;
    width: 1000px;
}
div#three {
    height: 1000px;
}
</style>
...
<div id="one">Hello World!</div>
<div id="two"></div>
<div id="three"></div>

I would like "Hello World!" to move horizontally with the window when the user scrolls horizontally. But I DON'T want it to move vertically with the window when the user scrolls vertically. What is the best way to do this? I'm using Bootstrap and jQuery UI, in case those might help. However, I am also interested in a pure CSS solution.

Thanks in advance :-) ktm

Whenever you scroll the window, reposition the #one element to always be on screen. Also, #one should be position: absolute.

$(window).scroll(function () {
    $("#one").css({
        left: $(this).scrollLeft()
    });
});

Here's your fiddle with the new code: http://jsfiddle.net/9AUbj/15/

While I admit that a CSS-only solution would be cool, you can't apply positioning based on axis. With how fixed positioning works, you can't force a horizontal scroll on the document even if the fixed-position element extends outside.

However, this is very simple to do with jQuery

$(document).on('scroll', function () {
    $("#two").css('top', $(this).scrollTop());
});

This requires #two to be absolutely positioned.

http://jsfiddle.net/9AUbj/16/

i used this code

$(window).scroll(function () {
    $("#one").css({
        left: $(this).scrollLeft()
    });
});

and it works perfect on Chrome , but on internet explorer when i drag the horizontal scroll, the fixed content starts to flicker :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM