首页 > 解决方案 > 3列布局的高度问题(溢出)

问题描述

html,body{
  height: 100%;
}
#app{
  height: 100%;
  border: 2px solid black;
}
.row{
	display: flex;
	height: 100%;
}
.col-3 {
	width: 20%;
	background: red;
}
.col-6 {
	width: 60%;
	background-color:blue;
}
#large-item{
  height: 100%;
  width: 100%;
  background: yellow;
  
}
<div id="app">
	<div class="row">
		<div class="col-3">
			<h2>left column</h2>
		</div>
		<div class="col-6">
			<h2>middle column</h2>
      <div id="large-item">Large item</div>
		</div>
		<div class="col-3">
			<h2>right column</h2>
		</div>
	</div>
  </div>

我按照 w3cschools 的说明创建了一个 3 列布局。问题是如果我将 html,body height 设置为 100%,列中的大项会溢出,这很难看。我怎样才能让它像自动添加滚动条一样响应并且背景颜色仍然填充列?

标签: css

解决方案


我建议你将高度设置为.col-6 > h2to30px#large-itemheight to calc(100% - 70px);。我们减去是70px因为30pxh2 的高度和 h220px的边距(顶部 + 底部 = 40px)。所以70px我们需要减去 30px + 40px。

Update 1: You will need to add parent container for large item to see the scrollbar when it has more content. And set it's height to calc(100% - 70px); and set overflow:auto;. To see the scrollbar, you can set the height of the large-item to 500px (for example)..

See the snippet.

html,body{
  height: 100%;
}
#app{
  height: 100%;
  border: 2px solid black;
}
.row{
	display: flex;
	height: 100%;
}
.col-3 {
	width: 20%;
	background: red;
}
.col-6 {
	width: 60%;
	background-color:blue;
}
#large-item-container{
  overflow:auto;
  height: calc(100% - 70px);
}
.col-6 > h2{
  height:30px;
}
#large-item{
  height:500px;
  width: 100%;
  background: yellow;
  
}
<div id="app">
	<div class="row">
		<div class="col-3">
			<h2>left column</h2>
		</div>
		<div class="col-6">
			<h2>middle column</h2>
      <div id="large-item-container">
        <div id="large-item">Large item</div>
      </div>
		</div>
		<div class="col-3">
			<h2>right column</h2>
		</div>
	</div>
  </div>

https://jsfiddle.net/nimittshah/rkuf49np/1/

If you want to add scrollbar for whole col-6 then its even easier. You don't need large-item-container.

See this

Enjoy! :)


推荐阅读