2016-12-31 206 views
3

我有两列的flexbox布局。如何使用固定在flex布局中的位置?

左列固定,右列可滚动。

你怎么能这样做?

看看下面的代码:

#parent { 
 
    display: flex; 
 
} 
 
#left { 
 
    flex-grow: 1; 
 
} 
 
#left div { 
 
    position: fixed; 
 
    background: blue; 
 
    top: 0; 
 
    left: 0; 
 
    height: 100vh; 
 
} 
 
#right { 
 
    flex-grow: 5; 
 
    background: red; 
 
    height: 300vh; 
 
}
<div id="parent"> 
 
    <div class="child" id ="left"> 
 
    <div> 
 
     ABC 
 
    </div> 
 
    </div> 
 
    <div class="child" id ="right"> 
 
    DEF 
 
    </div> 
 
</div>

Fiddle

+0

如何拨弄你不正是你描述? –

+0

@Dan Farrell - 固定div的宽度不是父母的宽度。在代码中添加了一些细节。 – jonhue

+0

我不认为你想要什么是可能的。您必须为边栏设置宽度,或者使用JavaScript动态计算宽度。 – sol

回答

1

如果我理解你的要求,你想要正确的滚动和左侧被固定。这可以在不使用固定位置的情况下完成。

我个人建议不要使用固定位置,除非它是绝对必要的,因为它可能会在移动设备上产生一些不需要的行为,并且您可能会失去优惠,例如flexbox优惠。

html, body { 
 
    margin: 0; 
 
} 
 
#parent { 
 
    display: flex; 
 
    height: 100vh; 
 
} 
 
#left { 
 
    flex-grow: 1; 
 
    background: blue; 
 
} 
 
#right { 
 
    flex-grow: 5; 
 
    background: red; 
 
    overflow: auto; 
 
} 
 
#right div { 
 
    height: 300vh; 
 
}
<div id="parent"> 
 
    <div class="child" id ="left"> 
 
     ABC 
 
    </div> 
 
    <div class="child" id ="right"> 
 
    <div> 
 
     DEF 
 
    </div> 
 
    </div> 
 
</div>

3

在这里你去

#parent { 
 
    position: fixed; 
 
    top: 0; 
 
    left: 0; 
 
    bottom: 0; 
 
    right: 0; 
 
    display: flex; 
 
    align-items: stretch; 
 
} 
 
#left { 
 
    flex-grow: 1; 
 
    background: lightgray; 
 
} 
 
#right { 
 
    flex-grow: 5; 
 
    background: red; 
 
    overflow-y: auto; 
 
} 
 
.scroll { 
 
    height: 300vw; 
 
}
<div id="parent"> 
 
    <div class="child" id="left"> 
 
    <div> 
 
     ABC 
 
    </div> 
 
    </div> 
 
    <div class="child" id="right"> 
 
    <div class="scroll"> 
 
     DEF 
 
    </div> 
 
    </div> 
 
</div>

2

您在评论中写道:

固定div的宽度是不是父母的宽度。

当添加到position: fixed的元素,从该文件和位置的其相到视正常流动移除。

固定元素没有理由在HTML结构中识别父元素的宽度。

您可以通过固定整个布局来达到目的(like in this answer)。否则,您需要一个JavaScript替代方案。