10

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>
Graham
  • 6,484
  • 2
  • 35
  • 39
  • Doesn't `overflow: auto;` on `main` solve it? – Asons Oct 23 '17 at 15:01
  • 1
    An initial setting on flex items is `min-width: auto`. This means that an item cannot be shorter than its content. That's why the item in your case is expanded, causing a horizontal scrollbar on the viewport. You can override this default with `min-width: 0` or `overflow` with any value other than `visible`. https://jsfiddle.net/e6g70uho/1/ – Michael Benjamin Oct 23 '17 at 15:22

1 Answers1

3

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>
Maxwell s.c
  • 1,583
  • 15
  • 29