I have a simple flexbox layout with two items; one fluid width and the other fixed. When the fluid item contains children that are wider / taller than itself, this causes the page to scroll, rather than the fluid item itself.
I have tried solutions to a few similar questions but none seem to work for me. As someone who hasn't used flexbox very much, I feel like I'm missing something obvious...
EDIT:
Adding overflow:auto
to .main
fixes the scrolling, thanks. However my example was simplified somewhat; I am also attempting to center the child item both vertically and horizontally, using flexbox align-items
and justify-content
. When this is applied, the main
element becomes unscrollable.
EDIT 2
I used the margin:auto
trick on the child item as specified at Can't scroll to top of flex item that is overflowing container to fix the second issue.
* {
margin: 0;
}
html, body {
height: 100%;
}
.container {
display: flex;
height: 100%;
}
.main {
flex: 1;
height: 100%;
background: green;
overflow: auto;
display: flex;
align-items: center;
justify-content: center;
}
.sidebar {
flex: 0 0 200px;
background: blue;
height: 100%;
}
.item {
width: 2000px;
height: 50px;
background: red;
}
<div class="container">
<div class="main">
<div class="item">
When his is 2000px wide, it should scroll inside its parent.
</div>
</div>
<div class="sidebar">
200px wide sidebar
</div>
</div>
You need to apply overflow:auto
to the parent. this property isn't automatic
* {
margin: 0;
}
html, body {
height: 100%;
}
.container {
display: flex;
height: 100%;
}
.main {
flex: 1;
height: 100%;
background: green;
overflow: auto;
}
.sidebar {
flex: 0 0 200px;
background: blue;
height: 100%;
}
.item {
width: 2000px;
height: 50px;
background: red;
}
<div class="container">
<div class="main">
<div class="item">
This is 2000px wide, and should scroll inside its parent. Instead, the body is scrolling.
</div>
</div>
<div class="sidebar">
200px wide sidebar
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With