Corne Lombaard
Corne Lombaard

Reputation: 17

make div change height dynamically

I have a page with 3 rows. The first row is a fixed height of 150px and the last row is a fixed height of 120px. I need the middle row to adjust according to the height of the window so that all three rows are visible and there are no scroll bars visible. The middle row must adjust dynamically so that even after loading if you move the browser window to another screen that is smaller the middle row must adjust accordingly. Secondly the middle row must have it's content aligned vertically middle and horizontally center. Any help is appreciated.

Upvotes: 0

Views: 112

Answers (5)

Kevin Farrugia
Kevin Farrugia

Reputation: 7489

Personally the cleanest solution is using flexbox:

.container {
  display: flex;
  flex-direction: column;
}

.dynamic {
  flex: 1 1 auto;
}

http://codepen.io/kevinfarrugia/pen/wzOqGo?editors=1100#0

Upvotes: 0

NoRyb
NoRyb

Reputation: 1544

I use flexboxes for these things: A Complete Guide to Flexbox

.container {  
  display: flex;
  flex: 1 1 auto;
  flex-direction: column;
}

.header {
  height: 50px;
  background-color: green;
  flex: 0 0;
}

.footer {
  height: 30px;  
  background-color: red;
  flex: 0 0;
}

.content {
  background-color: blue;
  flex: 1 1 auto;
  min-height: 50px;
}
<div class="container">
  <div class="header"></div>
  <div class="content"></div>
  <div class="footer"></div>
<div>

Upvotes: 0

Gabe Hiemstra
Gabe Hiemstra

Reputation: 269

As suggested, try using flexbox:

<style>
.container {
  display: flex;
  flex-flow: column wrap;
  align-items: stretch;
  height: 100%;
}
.row{}
.row.row1{height: 150px;}
.row.row2{flex: 1 1 auto;}
.row.row3{height: 120px;}
</style>

<div class="container">
  <div class="row row1">First row</div>
  <div class="row row2">Middle row</div>
  <div class="row row3">Final row</div>
</div>

Don't forget to add your vendor prefixes when using this.

Upvotes: 0

Ben Taliadoros
Ben Taliadoros

Reputation: 9491

CSS for the height:

.first-row {
   height: 150px;
}

.middle-row {
   height: calc(100vh - 150px - 120px);
}

.last-row {
   height: 120px;
}

Upvotes: 2

connexo
connexo

Reputation: 56803

Run the code snippet in full page mode (!). Use css calc function to automatically calculate the height of middle container.

body { 
  margin: 0; 
}
.top {
  background-color: #f0f0f0;
  height: 150px;
}
.bottom {
  background-color: #ddd;
  height: 120px;
}
.middle {
  background-color: teal;
  display: table-cell;
  height: calc(100vh - 270px);
  text-align: center;
  vertical-align: middle;
  width: 100vw;
}
<div class="top">TOP</div>
<div class="middle">MIDDLE</div>
<div class="bottom">BOTTOM</div>

Upvotes: 0

Related Questions