Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3 divs in fixed size container: 2 have fixed size, 1 should stretch

Tags:

html

css

Say I have a fixed size div, which contains 3 further divs:

  • The first and the last one have a fixed size as well, the middle one should fill the rest of the space

 #container {
   width: 100px;
   height: 100px;
 }
 #a,
 #c {
   height: 20px;
 }
 #b {
   height: 60px; // this should be a generic value...
 }
<div id="container">
  <div id="a">A</div>
  <div id="b">B</div>
  <div id="c">C</div>
</div>

How can I make the #b div to automatically stretch.

The three divs(#a, #b, #c) should fill the entire height of #container.

like image 735
Anton Harald Avatar asked Apr 20 '16 15:04

Anton Harald


3 Answers

You can use Flexbox and flex-direction: column, so if you set flex: 1 on #b it will take rest of free space.

#container {
  width: 100px;
  height: 100px;
  display: flex;
  flex-direction: column;
  border: 1px solid black;
}
#a,#c {
  height: 20px;
  background: lightblue;
}
#b {
  flex: 1;
  background: lightgreen;
}
<div id="container">
  <div id="a">A</div>
  <div id="b">B</div>
  <div id="c">C</div>
</div>

Update: I guess you could do same thing with css tables Fiddle

like image 65
Nenad Vracar Avatar answered Oct 14 '22 01:10

Nenad Vracar


Flexbox was made for this exact problem. it's magic! Note: Include webkit for better support.

html,body{height:100%}
#container {
  width: 100px;
  height: 100px;
  display:-webkit-flex;
  display:flex;
  -webkit-flex-direction:column;
  flex-direction:column;
}

#a, #c {
  height: 20px;
  background:#333;
}

#b {
  height: 100%; // this should be a generic value...
  background:#eee;
}
<div id="container">
   <div id="a">A</div>
   <div id="b">B</div>
   <div id="c">C</div>
</div>
like image 20
DreamTeK Avatar answered Oct 14 '22 03:10

DreamTeK


use CSS3 calc()

body,
html {
  height: 100%;
  margin: 0
}
#container {
  width: 100px;
  height: 100%;
}
#a,
#c {
  height: 20px;
  background: red
}
#b {
  height: calc(100% - 40px);
  background: green
}
<div id="container">
  <div id="a">A</div>
  <div id="b">B</div>
  <div id="c">C</div>
</div>

If you want to support IE8, you can use display:table/table-row

body {
  margin: 0
}
#container {
  width: 100px;
  height: 100px;
  display: table
}
#container > div {
  display: table-row
}
#a,
#c {
  height: 20px;
  background: red
}
#b {
  background: green
}
<div id="container">
  <div id="a">A</div>
  <div id="b">B</div>
  <div id="c">C</div>
</div>
like image 31
dippas Avatar answered Oct 14 '22 02:10

dippas