仅滚动一列的网格布局

时间:2019-12-19 20:32:38

标签: html css css-grid

我想创建一个布局,其中左侧部分留在同一位置,并且只能滚动右侧。但是当我使用位置:固定左侧部分变为视口的完整宽度和高度。

.container {
        position: relative;
        margin: 0;
        padding: 0;
        width: 100%;
        display: grid;
        grid-template-columns: 40% 60%;
}

.left {
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background-color: red;
}

.right {
    height: 200vh;
    background-color: blue;
}
<div class="container">
    <div class="left">
    </div>
    <div class="right">
    </div>
</div>

3 个答案:

答案 0 :(得分:1)

有一种简便的方法可以使用flex-box实现您想要的。唯一要做的就是将右侧的内容包装到具有已定义的height和CSS样式overflow-y: scroll;

的元素中

body {
    margin: 0;
    padding: 0;
}
.container {
    width: 100vw;
    height: 100vh;
    display: flex;
}

.left {
    height: 100%;
    width: 40%;
    background-color: red;
}

.right {
    height: 100%;
    overflow-y: scroll;
    width: 60%;
    background-color: blue;
}

.right-content {
    height: 200vh;
}
<div class="container">
    <div class="left">
      left content
    </div>
    <div class="right">
      <div class="right-content">
        right content
      </div>
    </div>
</div>

答案 1 :(得分:1)

我创建了正确的内容,这在正确的父div中造成了溢出。

*{
   margin: 0;
   padding: 0;
 }
.container {
        position: relative;
        margin: 0;
        padding: 0;
        width: 100%;
        height: 100vh;
        display: grid;
        grid-template-columns: 40% 60%;
}

.left {
    /*position: fixed;
    top: 0;
    left: 0;*/
   /* height: 100%;
    width: 100%;*/
    background-color: red;
}

.right {
    overflow-y: scroll;
    height: 100vh;
    background-color: blue;
}

.right_content{
   height: 200vh
 }
<div class="container">
    <div class="left">
  LEFT
    </div>
    <div class="right">
        <div class="right_content">RIGHT</div>
    </div>
</div>

答案 2 :(得分:1)

我玩过它。

如果您将左右类的位置设置为“内联”,则这些框将仅放在容器div中,并按照您的意愿彼此紧随其后。固定后,它将按照您的指定将其设置为0,0,但我认为在工作流之外,您的第二个div将从其父div继承并使用相对位置,因此它也为0,0(它没有位置声明。

也可以将您的左侧高度更改为“ 100vh”。由于右边的一个为“ 200vh”,所以100%时它也可以扩展为200vh。

因此您的代码将如下所示

#container {
    display: grid;
    position: relative;
    margin: 0;
    padding: 0;
    width: 100%;
    grid-template-columns: 40% 60%;
}
#left {
position: inline;
height: 100vh;
background-color: red;
}

#right {
position: inline;
height: 200vh;
background-color: blue;
}