CSS Sticky - 如何粘在一边以填充可用高度?

标签 css css-position sticky

我想创建网格布局,并且我想将其粘在 top: 0 上并填充所有剩余高度,例如100% 的高度,当我向下滚动时,我需要将旁边的高度更改为 100% 减去页脚高度。不用JS也能完成吗?

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.grid {
  display: grid;
  grid-template-areas: "aside content"
    "footer footer";
  grid-template-columns: 20rem 1fr;
}

aside {
  grid-area: aside;
  background-color: red;

}
nav {
  font-size: 2rem;
  color: black;
  position: sticky;
  top: 0;
  
  height: 100%;
  background-color: yellow;
}
main {
  grid-area: content;
  background-color: green;
  height: 150vh;
}
footer {
  grid-area: footer;
  background-color: blue;
  height: 10rem;
}

ul {
  list-style: none;
}
<div class="grid">
  <aside>
  <nav>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
    </ul>
  </nav></aside>
  <main>Content</main>
  <footer>Footer</footer>
</div>

最佳答案

height:100% 替换为 min-height:100vh

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.grid {
  display: grid;
  grid-template-areas: "aside content"
    "footer footer";
  grid-template-columns: 20rem 1fr;
}

aside {
  grid-area: aside;
  background-color: red;

}
nav {
  font-size: 2rem;
  color: black;
  position: sticky;
  top: 0;
  
  min-height:100vh;
  background-color: yellow;
}
main {
  grid-area: content;
  background-color: green;
  height: 150vh;
}
footer {
  grid-area: footer;
  background-color: blue;
  height: 10rem;
}

ul {
  list-style: none;
}
<div class="grid">
  <aside>
  <nav>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
    </ul>
  </nav></aside>
  <main>Content</main>
  <footer>Footer</footer>
</div>

关于CSS Sticky - 如何粘在一边以填充可用高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63245004/

相关文章:

html - 在 css 中对齐跨度、段落和 anchor

javascript - 我怎样才能有 2 个具有动态高度值的粘性标题

javascript - 使用滚动事件和添加类的动画标题

css - 等待 CSS 在 nextjs 静态站点上加载?

css - 悬停时隐藏绝对定位的div

Android webview 'fixed positioning'替代方案

html - 根据先前的内容调整 HTML span 元素的位置

html - 在使用 Bootstrap 粘性 header 时遇到问题

css - 滚动到底部时,模态底部的填充会弄乱固定标题

jquery - 更改 css 背景属性在 IE 中不起作用