Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox item with scrollable content [duplicate]

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>
like image 482
Graham Avatar asked Oct 23 '17 14:10

Graham


1 Answers

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>
like image 160
Maxwell s.c Avatar answered Nov 10 '22 07:11

Maxwell s.c