Tuesday, March 1, 2011

How do I make a div that stays in a fixed position regardless of where you are on the page?

Case example: I have a long list of items, and when I put my mouse over this div changes to that picture of that item. No matter where you scroll to, the div remains in a fixed position.

Sort of like a frame.

From stackoverflow
  • the div remains in a fixed position.

    position: fixed? Test it here.

  • Use the CSS property position:fixed.

    Example: <div id="items" style="position: fixed; top: 20px; right: 20px">Hello there!</div>

  • Absolute positioning:

    <body>
        <div style="position: absolute; top: 0; right: 0; width: 100px; height: 100px;">
        </div>
    </body>
    
    Guffa : That keeps the element in a fixed position relative to the page, I think that the OP want's it relative to the window.
    Dustin Laine : @Guffa - I don't think it is clear in message, I saw two fixed position answers and posted this to provide an alternative as I am unclear of his desired outcome.
  • Are you asking about div in fixed position? If you want to this the div by css itself, you can use the paramater like

    height:0px;
    left:0px;
    position:absolute;
    top:0px;
    width:0px;
    z-index:1;
    
    Guffa : That keeps the element in a fixed position relative to the page, I think that the OP want's it relative to the window.
    Karthik : Instead of fixed, we can absolute also
  • For newer browsers you can use position:fixed to make an element follow the window when you scroll.

    If you need to be compatible with older browsers, you would need a Javascript that gets the scroll offset from the window and changes the coordinates of an absolutely positioned element.

    fivetwentysix : Great answer thanks!

0 comments:

Post a Comment