带有固定侧边栏的 CSS 网格

Rod*_*igo 2 css css-grid

我的网站上需要一个固定的标题和侧边栏,位于中央 div 之外。侧边栏应该有自己的滚动条,就像中央 div 一样。我认为网格布局是实现此目的的方法,但我无法避免主体显示公共滚动条,而不是每个容器显示自己的滚动条。

我该怎么做呢?网格确实是更简单的解决方案吗?

body {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto 1fr;
  margin: 0;
}

header {
  background-color: #add790;
  grid-column: 1/3;
  grid-row: 1;
  text-align: center;
}

main {
  grid-column: 1;
  grid-row: 2;
  display: flex;
  align-items: stretch;
}

nav {
  background-color: orange;
  padding: 1em;
  min-height: 0;
}

#divMain {
  padding: 1em;
}
Run Code Online (Sandbox Code Playgroud)
<header>
  <h1>Title</h1>
</header>
<main>
  <nav>
    <p>Navigation</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
    <p>Some text.</p>
  </nav>
  <div id='divMain'>
    <p>Here too there should be a local scrollbar.</p>
    <p>Here too there should be a local scrollbar.</p>
    <p>Here too there should be a local scrollbar.</p>
    <p>Here too there should be a local scrollbar.</p>
    <p>Here too there should be a local scrollbar.</p>
    <p>Here too there should be a local scrollbar.</p>
    <p>Here too there should be a local scrollbar.</p>
    <p>Here too there should be a local scrollbar.</p>
  </div>
</main>
Run Code Online (Sandbox Code Playgroud)

小智 7

接受的答案不是css-grid基于解决方案。所以我的答案就在这里。

body {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  margin: 0;
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: auto 1fr;
}

header {
  grid-column: 1/3;
  background-color: #add790;
  text-align: center;
}

main {
  overflow-y: auto;
  padding: 1em;
}

nav {
  overflow-y: auto;
  padding: 1em;
  background-color: orange;
}
Run Code Online (Sandbox Code Playgroud)
<header>
  <h1>Title</h1>
</header>
<nav>
  <p>Navigation</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
  <p>Some text.</p>
</nav>
<main id='divMain'>
  <p>Here too there should be a local scrollbar.</p>
  <p>Here too there should be a local scrollbar.</p>
  <p>Here too there should be a local scrollbar.</p>
  <p>Here too there should be a local scrollbar.</p>
  <p>Here too there should be a local scrollbar.</p>
  <p>Here too there should be a local scrollbar.</p>
  <p>Here too there should be a local scrollbar.</p>
  <p>Here too there should be a local scrollbar.</p>
</main>
Run Code Online (Sandbox Code Playgroud)