定位与位置:粘性



Codepen再现此问题。

我正在做一个个人项目,但遇到了一个奇怪的问题。正如你所看到的,我有三个部分,它们应该一个接一个地排列。由于position: sticky的性质,我希望它们在滚动后能粘在顶部。然而,它们有一个奇怪的偏移,只有第三部分在滚动后会粘在顶部。

//
$enable-sticky-sections: true;
$sticky-section-count: 3;
//
*,
::after,
::before {
box-sizing: border-box;
}
html {
font-family: -apple-system, BlinkMacSystemFont,
"Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans",
"Droid Sans", "Helvetica Neue", sans-serif;
font-size: 1rem;
line-height: 1.5;
}
body {
margin: 0;
}
body {
> {
section {
position: relative;
}
}
}
@if($enable-sticky-sections) {
body {
> {
section {
position: sticky;
min-height: 100vh;
@for $i from 1 through $sticky-section-count - 1 {
&:nth-of-type(#{$i + 1}) {
top: calc(#{100 * $i}vh - #{20 * $i}px);
z-index: #{100 * $i};
//
background-color: #{#2196f3 * $i};
//
}
}
}
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="src/css/page.css">
</head>
<body>
<section></section>
<section></section>
<section></section>
</body>
</html>

我忘记了position: stickyposition: relative一样工作,直到它滚动过去。这意味着我需要去:margin-top: -#{20 * $i}px;,而不是top: calc(#{100 * $i}vh - #{20 * $i}px);

以下是的工作示例

//
$enable-sticky-sections: true;
$sticky-section-count: 3;
//
*,
::after,
::before {
box-sizing: border-box;
}
html {
font-family: -apple-system, BlinkMacSystemFont,
"Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans",
"Droid Sans", "Helvetica Neue", sans-serif;
font-size: 1rem;
line-height: 1.5;
}
body {
margin: 0;
}
body {
> {
section {
position: relative;
}
}
}
@if($enable-sticky-sections) {
body {
> {
section {
position: sticky;
min-height: 100vh;
@for $i from 1 through $sticky-section-count - 1 {
&:nth-of-type(#{$i + 1}) {
margin-top: -#{20 * $i}px;
z-index: #{100 * $i};
//
background-color: #{#2196f3 * $i};
//
}
}
}
}
}
}
<section></section>
<section></section>
<section></section>

最新更新