如何使用相对于根级别元素的粘性位置



我想对位于页眉元素内部的元素使用粘性位置,但向下滚动时保持在页面顶部。现在我可以把它贴在页眉的顶部,而不是整页。例如,类似于本页标题的内容。我可以在css文件中使用标题选择器而不是nav,但在这种情况下,图像也会粘在我不想要的顶部。

nav {
position: sticky;
position: -webkit-sticky;
top: 0px;
}
ul {
list-style-type: none;
padding: 0px;
margin: 0px;
overflow: auto;
background-color: #333;
}
li {
float: left;
border-right: thin solid rgba(255, 255, 255, 0.2);
}
li:last-child {
border-right: none;
border-left: thin solid rgba(255, 255, 255, 0.2);
float: right;
}
a {
display: block;
color: white;
text-decoration: none;
padding: 10px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<header style="height: 500px;">
<img src="https://html.com/wp-content/uploads/html-hpg-sublime.png" alt="image" style="width: 100%; height: 300px;">
<nav>
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</nav>
</header>
<article style="height: 1000px">
some article here...
</article>
</body>
</html>

试试这个

nav {
position: sticky;
position: -webkit-sticky;
top: 0px;
}
ul {
list-style-type: none;
padding: 0px;
margin: 0px;
overflow: auto;
background-color: #333;
}
li {
float: left;
border-right: thin solid rgba(255, 255, 255, 0.2);
}
li:last-child {
border-right: none;
border-left: thin solid rgba(255, 255, 255, 0.2);
float: right;
}
a {
display: block;
color: white;
text-decoration: none;
padding: 10px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<img src="https://html.com/wp-content/uploads/html-hpg-sublime.png" alt="image" style="width: 100%; height: 300px;">
<nav>
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</nav>
<div>
<h3>Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.</h3>
</div>
</body>
</html>

最新更新