A191919 A191919 - 7 months ago 15
HTML Question

css flexible middle column layout

How to make

.col2
flexible so it will fill space between
.col1
and
.col3
. I tried percents, but it doesn't work. What's the best way to achieve this? Thanks.



body{
margin:0;
}
.header{
width:100%;
background:gray;
height:120px;
margin:0 auto;
}
.MainController{
width:100%;
clear:both;
}
.col1{
height:679px;
background:yellow;
width:150px;
float:left;
}
.col2{
height:679px;
background:black;
float:left;
width:20%;
}
.col3{
height:679px;
background:red;
width:300px;
float:right;
}

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="header"></div>
<div class="MainController">
<div class="col1"></div>
<div class="col2"></div>
<div class="col3"></div>
</div>
</body>
</html>




Answer

Method 1: Using calc:

You could calculate the width with calc. The .col2 will be 100% of the width minus the width of the two columns. So in this case:

calc: (100% - 450px); /*150px + 300px = 450px*/

Your code becomes:

body{
	margin:0;
}
.header{
	width:100%;
	background:gray;
	height:120px;
	margin:0 auto;
}
.MainController{
	width:100%;
	clear:both;
}
 .col1{
	height:679px;
	background:yellow;
	width:150px;
	float:left;
}
.col2{
	height:679px;
	background:black;
	float:left;
	width:calc(100% - 450px);
}
.col3{
	height:679px;
	background:red;
	width:300px;
	float:right;
}
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
	<div class="header"></div>
	<div class="MainController">
		<div class="col1"></div>
		<div class="col2"></div>
		<div class="col3"></div>
	</div>
</body>
</html>


Method 2: Using flexbox:

You could also use flexbox like Aziz suggested.

Just set your .col2 to have flex:1 and your .MainController to have display:flex. Like so:

body{
	margin:0;
}
.header{
	width:100%;
	background:gray;
	height:120px;
	margin:0 auto;
}
.MainController{
	width:100%;
	clear:both;
    display: flex;
}
 .col1{
	height:679px;
	background:yellow;
	width:150px;
	float:left;
}
.col2{
	height:679px;
	background:black;
	float:left;
    flex: 1;
}
.col3{
	height:679px;
	background:red;
	width:300px;
	float:right;
}
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
	<div class="header"></div>
	<div class="MainController">
		<div class="col1"></div>
		<div class="col2"></div>
		<div class="col3"></div>
	</div>
</body>
</html>


Browser support

Both methods are widely supported, however you might still want to check browser support here.

calc() support

flexbox support