“位置:粘性”如何进行?物业工作? [英] How does the "position: sticky;" property work?
问题描述
我想使导航栏在滚动到顶部时停留在顶部,但是它不起作用,我也不知道为什么。如果可以的话,请帮我,这是我的HTML和CSS代码:
I want to make the Navigation Bar stick to the top once I scroll to it, but it's not working and I have no clue why. If you can please help, here is my HTML and CSS code:
.nav-selections {
text-transform: uppercase;
letter-spacing: 5px;
font: 18px "lato",sans-serif;
display: inline-block;
text-decoration: none;
color: white;
padding: 18px;
float: right;
margin-left: 50px;
transition: 1.5s;
}
.nav-selections:hover{
transition: 1.5s;
color: black;
}
ul {
background-color: #B79b58;
overflow: auto;
}
li {
list-style-type: none;
}
<nav style="position: sticky; position: -webkit-sticky;">
<ul align="left">
<li><a href="#/contact" class="nav-selections" style="margin-right:35px;">Contact</a></li>
<li><a href="#/about" class="nav-selections">About</a></li>
<li><a href="#/products" class="nav-selections">Products</a></li>
<li><a href="#" class="nav-selections">Home</a></li>
</ul>
</nav>
推荐答案
严格定位是相对定位和固定定位的混合体。
...
必须指定一个阈值,且该阈值至少包含一个顶部
,右
,底部
或left
可使粘性定位发挥预期的作用。否则,将无法与相对位置区分开。
[来源:MDN ]
Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.
...
You must specify a threshold with at least one oftop
,right
,bottom
, orleft
for sticky positioning to behave as expected. Otherwise, it will be indistinguishable from relative positioning. [source: MDN]
因此,在您的示例中,您必须使用<$ c $来定义其应停留在最后的位置c> top 属性。
So in your example, you have to define the position where it should stick in the end by using the top
property.
html, body {
height: 200%;
}
nav {
position: sticky;
position: -webkit-sticky;
top: 0; /* required */
}
.nav-selections {
text-transform: uppercase;
letter-spacing: 5px;
font: 18px "lato", sans-serif;
display: inline-block;
text-decoration: none;
color: white;
padding: 18px;
float: right;
margin-left: 50px;
transition: 1.5s;
}
.nav-selections:hover {
transition: 1.5s;
color: black;
}
ul {
background-color: #B79b58;
overflow: auto;
}
li {
list-style-type: none;
}
<nav>
<ul align="left">
<li><a href="#/contact" class="nav-selections" style="margin-right:35px;">Contact</a></li>
<li><a href="#/about" class="nav-selections">About</a></li>
<li><a href="#/products" class="nav-selections">Products</a></li>
<li><a href="#" class="nav-selections">Home</a></li>
</ul>
</nav>
这篇关于“位置:粘性”如何进行?物业工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!