html - 无法固定左侧边栏

标签 html css bootstrap-4

<分区>

我有一个 id 为 sideNav 的左侧 div 和一个像这样的右侧 main div

#sideNav {
  background-color: #012d20;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  overflow: hidden;
  border-right-style: groove;
  height: 100vh;
}
<div class="row">
  <!-- navigation sidebar -->
  <div class="col-2 pt-5" id="sideNav">
    ...
  </div>

  <!-- main content area -->
  <main class="col-10">
    ...
  </main>
</div>

代码有效,但 main 的左侧部分现在位于 sideNav 后面。当我删除 sideNav css 的位置属性时,我的 div 再次正确显示,但 sideNav 不再固定并随页面滚动。

如何固定 sideNav 并正确显示我的 div?

最佳答案

这对您不起作用的原因是行的显示类型为 flex,因此下面的所有列都适合该行。

然后,您的 cols 将按其给定值进行间隔,例如col-3 col-4 等

通过更改列显示类型(在您的示例中为 fixed),您将其从 flex 间距中移除,因此您的主导航将向左移动,因为您没有偏移它。

要解决这个问题,不要像其他人建议的那样添加填充,BootStrap 有处理这个问题的类。相反,将 offset-2 添加到您的主导航,并保持其他一切不变。

示例片段

#sideNav {
  background-color: #012d20;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  overflow: hidden;
  border-right-style: groove;
  height: 100vh;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<div class="row">
  <!-- navigation sidebar -->
  <div class="col-2 pt-5" id="sideNav">
    ...
  </div>

  <!-- main content area -->
  <main class="col-10 offset-2">
    ...
  </main>
</div>

关于html - 无法固定左侧边栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55139537/

上一篇:javascript - 更改显示中居中按钮的动画方向(持续时间)

下一篇:css - 使用 CSS 模块时无法在 Sass 中解析图像

相关文章:

html - 如何在 div 元素中水平居中按钮元素?

css - PIE 圆 Angular 不起作用

html - CSS,垂直对齐在 Mozilla Firefox 中不能正常工作

html - 如何使用SWF作为正文背景?

html - Bootstrap 导航链接未打开

html - 如何删除CSS中的 ImageView 类

javascript - 修复不能在 html 中使用 bootstrap 4

css - 如何为事件的 Bootstrap 4 导航栏元素添加背景颜色

reactjs - React Bootstrap Forms : <Form. Control.Feedback></Form.Control.Feedback> 在验证为 false 时不显示

javascript - Slick JS 仅在查看 html 时不起作用