位置:子元素上的粘性行为,而父元素不粘性? [英] Position: sticky behavior on a child element whilst the parent is not sticky?

查看:43
本文介绍了位置:子元素上的粘性行为,而父元素不粘性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现我不确定是否应该实现的目标.请注意,我正在寻找仅CSS的解决方案,我知道我可以使用JS解决此问题,但我不想这么做.

考虑以下笔: https://codepen.io/fchristant/pen/PjoKOq

第二个导航栏(深色)是粘性的,向下滚动时,它将停留在视口的顶部.第一个导航栏(灯光)不是粘性的,它只会滚动开.

但是,该浅色导航栏具有一个子元素,该子元素很粘.这样的想法是,父级将滚动离开,而子级仍会粘住,并与第二个导航栏(粘性)有效融合.

但是,这不起作用.因此,我的问题是:在父级中不具有粘性的子级元素根本有可能存在吗?

HTML:

 < div class ="site_header">网站标题< div class ="site_header_child">黏</div></div>< div class ="site_nav">网站标题</div> 

CSS:

  .site_header {显示:flex;位置:相对;宽度:100%;内边距:10px;背景:#eee;}.site_header_child {边框:1px纯红色;margin-left:auto;位置:粘性;z-index:2;顶:0;右:20px;}.site_nav {显示:块;位置:粘性;内边距:10px;背景:#333;颜色:#fff;位置:粘性;z-index:1;顶:0;} 

解决方案

在这种情况下无法使用粘性.尽管可以通过其他方式达到相同的效果.您可以简单地使用固定"定位,粘性孩子将保持原样.

  .site_header_child {位置:固定;顶部:10px;背景:#eee;} 

演示: https://codepen.io/anon/pen/VMWovv

I'm trying to achieve something that I'm not sure is supposed to be possible at all. Note that I'm looking for a CSS-only solution, I know I can solve this with JS, but I don't want to.

Consider the following pen: https://codepen.io/fchristant/pen/PjoKOq

The second navigation bar (dark) is sticky, as you scroll down, it will stick to the top of the viewport. The first navigation bar (light) is not sticky, it will simply scroll away.

However, that light navigation bar has a child element that is sticky. The idea is that the parent will scroll away, yet the child sticks, effectively blending with the second navigation bar (which is sticky).

This does not work, however. Hence my question: is it possible at all to have a sticky child element inside a parent that is not sticky?

HTML:

<div class="site_header">
  Site header
  <div class="site_header_child">
    sticky
  </div>
</div>
<div class="site_nav">
  Site header
</div>

CSS:

.site_header {
  display:flex;
  position:relative;
  width:100%;
  padding:10px;
  background:#eee;
}

.site_header_child {
  border:1px solid red;
  margin-left:auto;
  position:sticky;
  z-index:2;
  top:0;
  right:20px;
}

.site_nav {
  display: block;
  position:sticky;
  padding:10px;
  background:#333;
  color:#fff;
  position:sticky;
  z-index:1;
  top:0;
}

解决方案

It is not possible to use sticky in such case. The same effect can be achieved by other means though. You can simply use "fixed" positioning and the sticky child will stay were it was.

.site_header_child {    
  position:fixed;
  top:10px;
  background:#eee;
}

Demo: https://codepen.io/anon/pen/VMWovv

这篇关于位置:子元素上的粘性行为,而父元素不粘性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆