CSS position:fixed inside a positioned element

2020-02-17 06:11发布

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.

8条回答
对你真心纯属浪费
2楼-- · 2020-02-17 06:48

Seems, css transforms can be used

"‘transform’ property establishes a new local coordinate system at the element",

but ... this is not cross-browser, seems only Opera works correctly

查看更多
Juvenile、少年°
3楼-- · 2020-02-17 06:50

The current selected solution appears to have misunderstood the problem.

The trick is to neither use absolute nor fixed positioning. Instead, have the close button outside of the div with its position set to relative and a left float so that it is immediately right of the div. Next, set a negative left margin and a positive z index so that it appears above the div.

Here's an example:

#close
    {
        position: relative;
        float: left;
        margin-top: 50vh;
        margin-left: -100px;
        z-index: 2;
    }

#dialog
    {
        height: 100vh;
        width: 100vw;
        position: relative;
        overflow: scroll;
        float: left;
    }

<body> 
    <div id="dialog">
    ****
    </div>

    <div id="close"> </div>
</body>
查看更多
登录 后发表回答