Can I position an element fixed relative to parent?
The CSS specification requires that position:fixed
be anchored to the viewport, not the containing positioned element.
If you must specify your coordinates relative to a parent, you will have to use JavaScript to find the parent's position relative to the viewport first, then set the child (fixed) element's position accordingly.
ALTERNATIVE: Some browsers have sticky
CSS support which limits an element to be positioned within both its container and the viewport. Per the commit message:
sticky
... constrains an element to be positioned inside the intersection of its container box, and the viewport.A stickily positioned element behaves like position:relative (space is reserved for it in-flow), but with an offset that is determined by the sticky position. Changed isInFlowPositioned() to cover relative and sticky.
Depending on your design goals, this behavior may be helpful in some cases. It is currently a working draft, and has decent support, aside from table elements. position: sticky
still needs a -webkit
prefix in Safari.
See caniuse for up-to-date stats on browser support.
Let me provide answers to both possible questions. Note that your existing title (and original post) ask a question different than what you seek in your edit and subsequent comment.
To position an element "fixed" relative to a parent element, you want position:absolute
on the child element, and any position mode other than the default or static on your parent element.
For example:
#parentDiv { position:relative; }
#childDiv { position:absolute; left:50px; top:20px; }
This will position childDiv
element 50 pixels left and 20 pixels down relative to parentDiv's position.
To position an element "fixed" relative to the window, you want position:fixed
, and can use top:
, left:
, right:
, and bottom:
to position as you see fit.
For example:
#yourDiv { position:fixed; bottom:40px; right:40px; }
This will position yourDiv
fixed relative to the web browser window, 40 pixels from the bottom edge and 40 pixels from the right edge.