Html 滚动容器内的 CSS 位置元素“固定”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11261270/
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 01:21:10  来源:igfitidea点击:

CSS position element "fixed" inside scrolling container

htmlcssposition

提问by Siggi Gross

i wonder if anyone has found a solution for this?

我想知道是否有人为此找到了解决方案?

i am looking for a solution to attach an element to the top of a scrolling container

我正在寻找将元素附加到滚动容器顶部的解决方案

HTML:

HTML:

<div class="container">
  <div class="header">title</div>
  <div class="element">......</div>
  ... (about 10-20 elements) ...
  <div class="element">......</div> 
</div>

all "elements" have position:relative,

所有“元素”都有position:relative

the container has the following CSS:

容器具有以下 CSS:

.container {
  position:relative;
  width:200px;
  height:400px;
  overflow-y:scroll;
}

i want the header to stay on top of the container, independant of its scrolling position and the elements scrolling underneath.

我希望标题保持在容器的顶部,独立于其滚动位置和在下方滚动的元素。

the CSS so far:

到目前为止的 CSS:

.header {
  position:absolute; /* scrolling out of view :-( */
  z-index:2;
  background-color:#fff;
}
.element{
  position: relative;
}

all elements are block elements, and i can not move the header outside of the container. jquery is no option at this point.

所有元素都是块元素,我无法将标题移到容器外。jquery 在这一点上是没有选择的。

回答by Arkana

I think your solution pass with position:sticky. Seems it's like position:fixedbut respects the relative position to his parent.

我认为您的解决方案通过position:sticky. 看起来很像position:fixed但尊重他父母的相对位置。

Unfortunately this is an experimental feature, and is only supported in Chromium. You can see more details in this test page.

不幸的是,这是一项实验性功能,仅在 Chromium 中受支持。您可以在此测试页中查看更多详细信息。

The pure css solution that comes into my mind is with a little change of the markup. You can set a container only for the "elements" as this:

我想到的纯 css 解决方案是对标记稍作改动。您可以仅为“元素”设置容器,如下所示:

<div class="cont_elements">
      <div class="element">......</div>
      .....
</div>

And give the overflow to this inner container. Now, your header sticks at top.

并将溢出物注入这个内部容器。现在,您的标题位于顶部。

Here's a working demo.

这是一个工作演示

回答by Robin Maben

jQuery UI added a position()utility method just for this purpose that would make your life easier.

jQuery UI 添加了一个position()实用程序方法只是为了这个目的,这将使您的生活更轻松。

$( "#someElement" ).position({
    of:  //Element to position against,
    my:  //which position on the element being positioned,
    at:  //which position on the target element eg: horizontal/vertical,
    offset:  // left-top values to the calculated position, eg. "50 50"
});

Definitely helped me.

绝对帮助了我。

回答by waterplea

Here's the solution I came up with using position: sticky(so no IE unfortunately):

这是我想出的解决方案position: sticky(不幸的是没有 IE):

https://codepen.io/waterplea/pen/JjjMXzR

https://codepen.io/waterplea/pen/JjjMXzR

The idea is to have a 0 height sticky container on top of the scrolling container, so it sticks but doesn't push any of the content below and then position your stuff absolutely inside it. This way you have width but do not have height, so you can only kinda position something from the top like I did with button in my example.

这个想法是在滚动容器的顶部有一个 0 高度的粘性容器,所以它会粘住但不会推动下面的任何内容,然后将你的东西绝对放在里面。这样你有宽度但没有高度,所以你只能像我在我的例子中使用按钮那样从顶部定位一些东西。

EDIT: Found a way to make it have 100% height and not push the content below using float. Updated the codepen. Had to use calc(100% - 1px)because of this bug in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1612561

编辑:找到了一种方法,使其具有 100% 的高度,而不是使用浮动将内容推送到下方。更新了代码笔。calc(100% - 1px)由于 Firefox 中的这个错误,不得不使用:https: //bugzilla.mozilla.org/show_bug.cgi?id=1612561

回答by Madara's Ghost

The solution in this case would be to pop the title outside of the scrolling element:

这种情况下的解决方案是在滚动元素之外弹出标题:

<div class="header">title</div>
<div class="container">
    <div class="element">......</div>
    <div class="element">......</div>
</div>

Although you should probably have better semantic elements if possible (just guessing here):

虽然如果可能的话,你可能应该有更好的语义元素(只是在这里猜测):

<h3>title</h3>
<ul>
    <li>......</li>
    <li>......</li>
</ul>

回答by Ocool Sanni

The best answer you will ever find for such a solution is from this link How to fixed scroll div after certain height and stop after reach other div? I hope this saves someone some googling time

对于此类解决方案,您将找到的最佳答案来自此链接如何在特定高度后固定滚动 div 并在到达其他 div 后停止? 我希望这可以为某人节省一些谷歌搜索时间

    var navWrap = $('#navWrap'),
        nav = $('nav'),
        startPosition = navWrap.offset().top,
        stopPosition = $('#stopHere').offset().top - nav.outerHeight();
    
    $(document).scroll(function () {
        //stick nav to top of page
        var y = $(this).scrollTop()
        
        if (y > startPosition) {
            nav.addClass('sticky');
            if (y > stopPosition) {
                nav.css('top', stopPosition - y);
            } else {
                nav.css('top', 0);
            }
        } else {
            nav.removeClass('sticky');
        } 
    });
body {
    height:1600px;
    margin:0;
}
#navWrap {
    height:70px
}
nav {
    height: 70px;
    background:gray;
}
.sticky {
    position: fixed;
    top:0;
}

h1 {
    margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit morb??,o vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
<div id="navWrap">
    <nav>
         <h1>I stick to the top when you scroll down and unstick when you scroll up to my original position</h1>
    </nav>
</div>

<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit??, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit morb??,o vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
<br>
<div id="stopHere">
<h3 style="color:red">I want it stop fixed scrolling here. If I'm back to scrolling up, It will follow also to original position.</h3>
</div>
<br>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit morb??,o vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit??, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit morb??,o vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit??, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit morb??,o vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>