Place the Div "Fixed" Vertically and "Absolute" horizontally in the "Position: Relative" Container Div

I'm looking for a way that I can create a div that will be fixed vertically on the page, so if the user scrolls down, the div stays in the same place on the page. But adjust it horizontally, so if the user’s screen is narrower than my web page, scrolling to the right or left will not cause the div to move from the screen and in some cases will remain either half visible at the edge of the screen or completely leave the page.

This div should be in the "Position: Relative" section.

I am sure that there is no way to assign different positions for the changing axis of the div, but this is the best way to describe the effect that I hope to achieve.

I have it so far, basically it is a fixed div within a relative div.

CSS

#container { position:relative; width:700px; height:1000px; top:50px; left:50px; background-color:yellow; } #blue-box{ position:fixed; width:100px; height:100px; background-color:blue; margin-top:20px; margin-left:400px; { 

HTML

 <div id="container"> <div id="blue-box"></div> </div> 

I also created jsFiddle to demonstrate this problem.

This works great for vertical, but if you resize your web browser so that it is smaller than the yellow box (container) and then scrolled horizontally, the blue box will move with the page. I hope this does not happen.

If this cannot be done using CSS, I would love to use JavaScript if it works with all modern browsers and IE7 and IE8. (This is why I added the JavaScript tag)

Can anyone help me out?

+8
javascript css scroll css-position
source share
2 answers

Using jQuery, use the scrollLeft () property of a document! It will work

 $(window).scroll(function(event) { $("#blue-box").css("margin-left", 400-$(document).scrollLeft()); }); 

see also

http://jsfiddle.net/zhQkq/9/

Good luck

Edit: if you want it to use your preset margin left rather than hardcoded β€œ400”, use

 $(window).scroll(function(event) { $("#blue-box").css("margin-left", $("#blue-box").css("margin-left")-$(document).scrollLeft()); }); 
+16
source share

Here's my solution (tested in Opera and Firefox): http://jsfiddle.net/cCH2Z/2 The trick is to specify right: 0px; , this will place the 0px field on the right border of the window.

-2
source share

All Articles