【问题标题】:Fixed column when vertically scrolling. Unfixed when horizontally scrolling. Pure CSS垂直滚动时固定列。水平滚动时不固定。纯 CSS
【发布时间】:2023-03-19 22:53:01
【问题描述】:

我有一个居中的页面,其中两列填充了窗口高度。 左栏固定的,因此在滚动时始终可见。 右栏包裹页面内容,通常比左栏大。

HTML:

<div class="main-container">
  <div class="col1">
    <p>Fixed column</p>
  </div>
  <div class="col2">
    <p>Content column</p>
  </div>
</div>

CSS:

.main-container {
  width: 300px;
  height: 100%;
  margin: 0 auto;
}

.col1 {
  position: fixed;
  width: 100px;
  height: 100%;
  background: fuchsia;
}

.col2 {
  width: 200px;
  margin-left: 100px;
  background: cyan;
}

当浏览器窗口窄于页面宽度(本例为300px)时,会出现水平滚动条,固定列会保持固定并飞过内容列。我想避免这种情况

我可以使用纯 CSS(无 Javascript)实现这种仅限垂直的修复吗?

请参阅full example Plunker

澄清:垂直滚动条必须是窗口滚动条,而不是.col2中的内部滚动条。

【问题讨论】:

    标签: html css


    【解决方案1】:

    Demo

    css

    .col1 {
        position: fixed;
        width: 100px;
        height: 100%;
        background: fuchsia;
        z-index: 1; /* z-index lower than than .col2 */
    }
    .col2 {
        position: relative; /* position needed for z-index to work */
        width: 200px;
        margin-left: 100px;
        background: cyan;
        z-index: 2; /* z-index higher than than .col1 */
    }
    

    【讨论】:

    • 这并不能解决“固定”列问题,它只是让流体列始终可见。
    • 那么你希望它表现如何?
    • 他想要实现的是左列在水平滚动时失去固定状态。
    【解决方案2】:

    我认为在您的情况下,您需要使用 media queries 或 twitter bootstrap

    【讨论】:

    • 其实我同时使用了媒体查询和Bootstrap,但是它们并不能解决这个具体的问题。
    【解决方案3】:

    只需将CSS属性z-index:-1;添加到固定列.col1,就可以了

    【讨论】:

    • 然后,它在 .col2 下飞行。我希望 .col1 保持其“绝对”位置。
    • 那么你想要的只是 .col2 上的滚动条吧?
    • 我想设置一个页面最小宽度(例如,920px)。在该宽度下,将显示一个水平滚动条,然后固定列可以与内容列重叠。
    【解决方案4】:

    您只能在 .col2 容器上使用绝对定位和溢出。这样,您的固定列仍然在垂直滚动上,而不是在水平滚动上。

    jsFiddle: http://jsfiddle.net/85fyC/

    CSS:

    html, body {
        height: 100%;
        overflow-y: hidden;
    }
    
    .main-container {
        position: relative;
        width: 300px;
        height: 100%;
        margin: 0 auto;
    }
    
    .col1 {
        position: absolute;
        width: 100px;
        height: 100%;
        background: fuchsia;
    }
    
    .col2 {
        width: 200px;
        height: 100%;
        margin-left: 100px;
        overflow: auto;
    }
    
    .col2 .inner {
        background: cyan;
    }
    
    .col2 .inner p {
        margin: 0;
    }
    

    【讨论】:

    • 它强制垂直滚动条在 .col2 中而不是在窗口中。我想使用窗口滚动条,就像在 Facebook 中一样。它与您的建议不兼容,但还是谢谢您;)
    • 我知道确实如此,但您要求的是纯 CSS 解决方案——您可能愿意接受妥协或转而使用 JS。
    猜你喜欢
    • 2019-03-27
    • 2012-12-25
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多