首页 > 解决方案 > 固定的可滚动侧边栏越过页面标题/标题

问题描述

我正在设计一个页面,其中我固定了高度为 100% 的侧边栏和右侧的主要内容。但问题是当我保留时它会越过标题/横幅top: 0;

如果我保持top: 1;侧边栏向下,但是当我滚动页面时,它会在侧边栏和标题之间创建一个空白区域,如图所示在此处输入图像描述

我希望我的侧边栏占据整个屏幕的 100% 高度,同时它不应该越过横幅。

我的代码是

#banner {
  width: 100%;
  height: 100px;
  background: skyblue;
}

.sidenav {
  height: 100%;
  width: 160px;
  position: fixed;
  z-index: 1;
  top: 1;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  padding-top: 20px;
}

.sidenav a {
  padding: 6px 8px 6px 16px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
}

.sidenav a:hover {
  color: #f1f1f1;
}

.main {
  margin-left: 160px;
  /* Same as the width of the sidenav */
  font-size: 28px;
  /* Increased text to enable scrolling */
  padding: 0px 10px;
}
<div id="banner">

</div>
<div class="sidenav">
  <a href="#about">About</a>

</div>

<div class="main">
  <h2>Sidebar</h2>
  <p>This sidebar is of full height (100%) and always shown.</p>

</div>

如果有任何技巧可以实现这一目标。谢谢。

标签: htmlcsssidebar

解决方案


您可以使用它使侧边栏的屏幕高度减去特定数量的像素,然后将其与底部对齐。

.sidenav {
  height: calc(100% - 50px);
  width: 160px;
  position: fixed;
  z-index: 1;
  bottom: 0;
  top: auto;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  padding-top: 20px;
}

也不top: 1是有效的 css,它需要一个单位,如 px、em 等。


推荐阅读