I have a positioned div whose content can be too long so scrollbars appear (overflow:auto
set). It functions as a dialog box in an ajax app. I want to fix a close button on it's right top corner so when the user scrolls the div it won't scroll away.
I tryed it with position:fixed; right:0; top:0
but it placed the button on the right top of the page not in the div (in firefox).
Is it possible to do this button placement using CSS only without hacking with the offsetWidth/Height in js on every scroll event?
ps: the div's height and width is not a fixed value it depends on the content's size and the browser window's size. User can also resize it if he want.
I know this is an old post but I had the same question but didn't find an answer that set the element fixed relative to a parent
div
. The scroll bar on medium.com is a great pure CSS solution for setting somethingposition: fixed;
relative to a parent element instead of the viewport (kinda*). It is achieved by setting the parentdiv
toposition: relative;
and having a button wrapper withposition: absolute;
and the button of course isposition: fixed;
as follows:working example
*Since fixed elements don't scroll with the page the vertical position will still be relative to the viewport but the horizontal position is relative to the parent with this solution.
I achieved to have an element with a fixed position (wiewport) but relative to the width of its parent.
I just had to wrap my fixed element and give the parent a width 100%. At the same time, the wrapped fixed element and the parent are in a div which width changes depending on the page, containing the content of the website. With this approach I can have the fixed element always at the same distance of the content, depending on the width of this one. In my case this was a 'to top' button, always showing at 15px from the bottom and 15px right from the content.
https://codepen.io/rafaqf/pen/MNqWKB
Position:fixed
gives an absolute position regarding the BROWSER window. so of course it goes there.While
position:absolute
refers to the parent element, so if you place your<div>
button inside the <div>
of the container, it should position where you meant it to be. Something likeEDIT: thanks to @Sotiris, who has a point, solution can be achieved using a position:fixed and a margin-left. Like this: http://jsfiddle.net/NeK4k/
Try position:sticky on parent div of the element you want to be fixed.
If your close button is going to be text, this works very well for me:
Then your
HTML
can just be:You can use the
position:fixed;
, but without setleft
andtop
. Then you will push it to the right usingmargin-left
, to position it in the right position you wish.Check a demo here: http://jsbin.com/icili5