CSS 固定相对于父 div 的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15169220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 21:51:23  来源:igfitidea点击:

Fixing position relative to parent div

csspositioncontainersparentfixed

提问by Windbrand

Is it possible to fix an element's position relative to the parent div, not the browser window?

是否可以固定元素相对于父 div的位置,而不是浏览器窗口

Say I have:

说我有:

<div id="pagecontainer">

    <div id="linkspage">

        <div class="sidelinks">
            <a href="#page1" class="link">Link 1</a>
            <p>
            <a href="#page2" class="link">Link 2</a>
            <p>
            <a href="#page3" class="link">Link 3</a>
            <p>
            <a href="#page4" class="link">Link 4</a>
            <p>
        </div>

        <div class="linkscontent">
            content of links page
        </div>

    </div>

    //OTHER PAGES

</div>

Basically a page with two sections, the left section is a list of links, while the right section is the page's content. I want the content to be scrollable, but the links to remain fixed to the parent #pagecontainer so they don't scroll when #pagecontainer scrolls, but they'll move when I scroll the entire browser window.

基本上有两个部分的页面,左侧部分是链接列表,而右侧部分是页面的内容。我希望内容是可滚动的,但链接要保持固定在父级 #pagecontainer 上,因此当 #pagecontainer 滚动时它们不会滚动,但是当我滚动整个浏览器窗口时它们会移动。

I've already tried the JQuery "fixto" plugin: https://github.com/bbarakaci/fixto. But I can't use that one because my pages fade in/out and the script bugs out when the parent element (#pagecontainer) has an alpha of 0, it thinks the parent element is gone and has nowhere to fix to.

我已经尝试过 JQuery“fixto”插件:https: //github.com/bbarakaci/fixto。但是我不能使用那个,因为当父元素 (#pagecontainer) 的 alpha 为 0 时,我的页面淡入/淡出并且脚本出错,它认为父元素已经消失并且无处可修复。

Thanks.

谢谢。

回答by zakangelle

Give the parent position: relative, like this:

给父母position: relative,像这样:

.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 0;
}

See DEMO.

演示

回答by Alen

I've created this CodePenfor you.

我已经为你创建了这个CodePen

From your description, it is half way there.

从你的描述来看,已经有一半了。

but they'll move when I scroll the entire browser window.

但是当我滚动整个浏览器窗口时它们会移动。

You will need to use iframeor some kind of JavaScript solution.

您将需要使用iframe或某种 JavaScript 解决方案。