flex取消子元素内容过多自动撑开

1,243 阅读1分钟

背景

页面中两个盒子,宽度需要适应,盒子都有阴影。使用flex布局,左右盒子分别的flex属性为5.而盒子2(.table)子元素内容较多,会自动撑开flex:5的盒子,造成页面横行滚动条。如图:

image.png 错误方案:为盒子2(.table)设置overflow:hidden,可以实现子元素不撑开盒子,但是阴影却消失了

image.png

正确方案:为盒子2(.table)设置width:0,子元素不撑开盒子,阴影也在

image.png 代码

<!DOCTYPE html>
		<html>
		<head>
			<title>测试flex超出</title>
			<style type="text/css">
				html {
				  min-height: 100%;
				  width: 100%;
				}
				body, {
				  height: 100%;
				}

				.chart-table {
				  display: flex;
				}
				.chart-table .chart .content,
				.chart-table .table .content {
				  background: #ffffff;
				  box-shadow: 1px 1px 3px 0px rgba(181, 181, 181, 0.5);
				  border-radius: 8px;
				  border: 1px solid #f8f8f8;
				  height: 350px;
				}

					/*盒子*/
				.chart-table .chart {
				  flex: 5;
				  margin-right: 30px;
				  min-width: 400px;
				}
				.chart-table .table {
				  flex: 5;
				  width: 0;	/*加上此行代码*/
				}
				.chart-table .table .content{
				   display: flex;
				   flex-wrap: wrap;
				   overflow: auto;
				   color: #fff
				}
					/*盒子内容*/
				.chart-table .cell {
				      width: 100%;
					    height: 200px;
					    background: #128758;
					    border-radius: 4px;
					    margin: 10px;
					    text-align: center;
					    line-height: 200px
				}
				</style>
		</head>
		<body>
			<div class="chart-table">
				<div class="chart">
					<div class="content">
					</div>
				
				</div>
					<!-- 盒子 -->
				<div class="table">
					<div class="content">
						<div class="cell">我是table可滚动内容</div>
						<div class="cell">我是table可滚动内容</div>
						<div class="cell">我是table可滚动内容</div>
						<div class="cell">我是table可滚动内容</div>
						<div class="cell">我是table可滚动内容</div>
					</div>
				</div>
			</div>
		</body>
		</html>