我已应用了显示我的问题的代码段。我正在尝试使.navigation
元素保持固定在彩色div的顶部,但是,对:0;使.navigation元素转到正文的右侧,而不是其父元素容器。为什么会这样?
*,
*:after,
*:before {
margin: 0;
padding: 0;
-webkit-box-sizing: border-box;
box-sizing: border-box;
text-decoration: none;
list-style-type: none;
color: rgba(0, 0, 0, 0.75);
}
body {
background-color: #f1f1f1;
font-family: 'Helvetica', 'Helvetica Neue', 'Arial', sans-serif;
line-height: 1.8rem;
}
.wrapper {
width: 70%;
margin: 0 auto;
}
.container {
position: relative;
}
.navigation {
display: flex;
flex-direction: column;
align-items: center;
position: fixed;
right: 0;
}
.navigation div {
padding: 20px;
font-weight: 600;
font-size: 1.3em;
}
section {
height: 100vh;
}
.one {
background-color: red;
}
.two {
background-color: blue;
}
.three {
background-color: green;
}
<main class='container wrapper'>
<nav class='navigation'>
<div>
About
</div>
<div>
Projects
</div>
<div>
Contact
</div>
</nav>
<section class='about one'>
</section>
<section class='projects two'>
<div class="">
<a href="#">Test1</a>
</div>
<div class="">
<a href="#">Test2</a>
</div>
<div class="">
<a href="#">Test3</a>
</div>
</section>
<section class='contact three'>
</section>
</main>
答案 0 :(得分:0)
位置fixed
总是相对于视口。您可以尝试将sticky
和float:right;
结合使用top:0;
,但是此解决方案在IE上不起作用。
*,
*:after,
*:before {
margin: 0;
padding: 0;
-webkit-box-sizing: border-box;
box-sizing: border-box;
text-decoration: none;
list-style-type: none;
color: rgba(0, 0, 0, 0.75);
}
body {
background-color: #f1f1f1;
font-family: 'Helvetica', 'Helvetica Neue', 'Arial', sans-serif;
line-height: 1.8rem;
}
.wrapper {
width: 70%;
margin: 0 auto;
}
.container {
position: relative;
}
.navigation {
display: flex;
flex-direction: column;
align-items: center;
/* modified part: */
position: sticky;
float: right;
top: 0;
}
.navigation div {
padding: 20px;
font-weight: 600;
font-size: 1.3em;
}
section {
height: 100vh;
}
.one {
background-color: red;
}
.two {
background-color: blue;
}
.three {
background-color: green;
}
<main class='container wrapper'>
<nav class='navigation'>
<div>
About
</div>
<div>
Projects
</div>
<div>
Contact
</div>
</nav>
<section class='about one'>
</section>
<section class='projects two'>
<div class="">
<a href="#">Test1</a>
</div>
<div class="">
<a href="#">Test2</a>
</div>
<div class="">
<a href="#">Test3</a>
</div>
</section>
<section class='contact three'>
</section>
</main>