Reputation: 1467
I have a flexbox layout with two columns.
The left column be fixed, while the right is scrollable.
How can you do that?
Take a look at the following code:
#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>
Upvotes: 16
Views: 32146
Reputation: 87191
If I understand your requirements, you want make the right scroll and the left be fixed. That can be done without the use of fixed position.
I would also personally recommend to not use fixed position, unless it is absolutely necessary, as it can have some unwanted behavior on mobile device, and you kind of loose the benefit non positioned solutions like flexbox
offer.
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>
Upvotes: 14
Reputation: 371231
You wrote in the comments:
the width of the fixed div is not the parents width.
When you add position: fixed
to an element, you remove it from the normal flow of the document and position it relative to the viewport.
The fixed element has no reason to recognize the parent's width in the HTML structure.
You may be able to achieve what you want by making the entire layout fixed (like in this answer). Otherwise, you'll need a JavaScript alternative.
Upvotes: 2
Reputation: 1943
here you go
#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>
Upvotes: 5