为什么我的固定元素位于整个屏幕的右侧,而不是其父元素的右侧?

问题描述 投票:0回答:1

我已应用了显示我的问题的代码段。我试图使.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>
html css
1个回答
0
投票

位置fixed始终相对于视口。您可以尝试将stickyfloat: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>
© www.soinside.com 2019 - 2024. All rights reserved.