【问题标题】:Fixed side bar is not scrolling with page contents固定侧栏不随页面内容滚动
【发布时间】:2017-05-13 20:07:32
【问题描述】:

我在页面右侧有一个固定的侧边栏 (position: fixed) 但它的内容并不完全可见,因为它没有随着页面滚动而滚动。我可以在.sidebar{} css 设置中添加overflow-y: scroll。但不希望侧边栏有单独的滚动条。有没有一个选项可以让它随着整页滚动而滚动。

这是我的侧边栏 CSS 设置:

.sidebar {
  text-align: center;
  padding: 2rem,1rem;
  color: rgba(255,255,255,.5);
  background-color: #202020;
  top: 0;
  bottom: 0;
}

如果你想调试看看出了什么问题,这里是实时运行的:https://pagefault.me

谢谢

【问题讨论】:

标签: css


【解决方案1】:

根据我在评论中建议的答案,我能够在 chrome 中工作以到达下面的 css。

1) 在 .sidebar-nav 组件中添加一些 css

nav.sidebar-nav {
    position: absolute;
    overflow-y: scroll;
    top: 100px; /*100px to give some room for the sidebar heading (without this, absolute position will make the nav overlap)*/
    left: 15px; /* you can make this zero and add `padding-left: 15px` */
    bottom: 15px; /* leave some room for copyright section */
    right: -17px; /*this may vary from browser to browser (i suggest using the width of the widest scrollbar, then adjust for padding-right)*/
    padding-right: 15px; /*padding to prevent the text from flowing off screen*/
}

2) .container 类变为

.sidebar .container{
    max-width: 38rem;
    padding-left: 1rem;
    padding-right: 1rem;
    margin-left: auto;
    margin-right: auto;
    height: 100%;
    position: relative;
    overflow: hidden;
}

3) 确保在将.sidebar-nav 设为绝对后,页脚位仍位于底部

.sidebar .container > p:last-of-type {
    position: absolute;
    bottom: -15px;
}

当然,正如原始解决方案中提到的,您必须在不同的浏览器中测试滚动条的宽度,以达到正确的宽度,以代替步骤 1 中的right: -17px

【讨论】:

    【解决方案2】:

    使用绝对位置而不是固定位置,因为您希望它与页面一起滚动。

    body {
      margin: 0;
      padding: 0;
      position: relative;
    }
    
    main {
      position: absolute;
      top: 0;
      left: 0;
      width: 80%;
      height: 300vh;
      background: beige;
    }
    
    aside {
      position: absolute;
      top: 0;
      right: 0;
      width: 20%;
      height: 300vh;
      background: black;
      color: white;
    }
    <main></main>
    <aside><aside>

    没有定位的弹性盒子解决方案:

    body {
      margin: 0;
      padding: 0;
      display: flex;
    }
    
    main {
      width: 80%;
      height: 300vh;
      background: beige;
    }
    
    aside {
      width: 20%;
      height: 300vh;
      background: black;
      color: white;
    }
    <main></main>
    <aside></aside>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多