html - 具有可滚动内容的 Flexbox 元素

标签 html css scroll flexbox

<分区>

我有一个简单的 flexbox 布局,其中包含两个元素;一个流体宽度和另一个固定。当流体元素包含比自身更宽/更高的子项时,这会导致页面滚动,而不是流体元素本身。

我已经尝试过一些类似问题的解决方案,但似乎没有一个对我有用。作为一个不太使用 flexbox 的人,我觉得我错过了一些明显的东西......

编辑:

overflow:auto 添加到 .main 修复了滚动,谢谢。但是,我的示例有所简化;我还尝试使用 flexbox align-itemsjustify-content 将子项垂直和水平居中。应用后,main 元素将变得不可滚动。

编辑 2

我在 Can't scroll to top of flex item that is overflowing container 指定的子项上使用了 margin:auto 技巧解决第二个问题。

* {
	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>

最佳答案

您需要将 overflow:auto 应用于父级。此属性不是自动的

* {
	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>

关于html - 具有可滚动内容的 Flexbox 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46892471/

相关文章:

html - CSS 右边距在带有溢出滚动的 Div 内不起作用

javascript - Ajax 调用后的新观察者原型(prototype)

javascript - 使用 Bootstrap 轮播显示预览(上一张和下一张图片)

html - &lt;input&gt; 超出 <div> block ,样式为 'float: right;'

ios UIPickerView 滚动太快

javascript - 当用户滚动位置到达它时将 javascript 加载到 div

html - 文本和包含另外两个 div 的 div 不是内联的

javascript - 为导航栏创建隐藏按钮

CSS 外边框

javascript - 如何在 fullCalendar 中更改标题的字体颜色