本文介绍了当元素包裹在另一个元素中时,为什么position:sticky不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验粘性导航,但遇到了问题.问题是,当我将导航栏放到其他元素中时,它不再具有粘性.

I am experimenting with sticky nav and I ran into problem. Problem is that when I put the nav in other element it's not anymore sticky.

.nav-wrapper{
  position: absolute;
  bottom: 0;
}

.nav-wrapper nav{
  position: sticky;
  top: 0;
}
    <div class="nav-wrapper">
     <nav>
      <a href="#"><li>Home</li></a>
      <a href="#"><li>About</li></a>
     </nav>
    </div>

推荐答案

位置粘性认为父元素的行为应具有应有的作用.在您的情况下,父元素的高度由sticky元素定义,因此该元素没有粘性.

Position sticky consider the parent element to behave as it should be. In your case the parent element has his height defined by the sticky element so there is no room for the element to be sticky.

添加边框以更好地查看问题:

Add border to better see the issue:

.nav-wrapper {
  position: absolute;
  bottom: 0;
  border: 2px solid;
}

.nav-wrapper nav {
  position: sticky;
  top: 0;
}

body {
  min-height:200vh;
}
<div class="nav-wrapper">
  <nav>
    <a href="#">
      <li>Home</li>
    </a>
    <a href="#">
      <li>About</li>
    </a>
  </nav>
</div>

现在将高度添加到父元素并查看发生了什么:

Now add height to the parent element and see what is happening:

.nav-wrapper {
  position: absolute;
  bottom: 0;
  border: 2px solid;
  height:80vh;
}

.nav-wrapper nav {
  position: sticky;
  top: 0;
}

body {
  min-height:200vh;
}
<div class="nav-wrapper">
  <nav>
    <a href="#">
      <li>Home</li>
    </a>
    <a href="#">
      <li>About</li>
    </a>
  </nav>
</div>

粘性行为表现良好,因为父元素上有足够的高度,可以在特定阈值之后固定该元素.

The sticky behavior is working fine because there is enough height on the parent element where the element can be fixed after a specific threshold.

这篇关于当元素包裹在另一个元素中时,为什么position:sticky不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 15:53