Jacksonkr Jacksonkr - 6 months ago 14
CSS Question

How to make inner div full height with unknown height parent?

I need

.col
to be 100% of
.row
height but you can see that the second
.col
falls short. How can I get this to work without using any "magic numbers"?

http://jsfiddle.net/b21g6fme/



.row {
position: relative;
background: #f99;
}
.col {
margin: 0 0 0 8px;
display: inline-block;
width: 40%;
position: relative;
vertical-align: top;
background: #999;
height: 100%;
}
.col:first-child {
margin: 0;
}
.item {
display: block;
position: relative;
top: 0;
margin: 12px 0 0 0;
min-height: 80px;
width: 100%;
outline: 4px solid black;
}
.item:first-child {
margin: 0;
}
.item.large {
min-height: 120px;
height: 100%;
}
.item.red {
background: #f00;
}
.item.blue {
background: #0f0;
}
.item.green {
background: #00f;
}

<div class="row">
<div class="col">
<div class="item red"></div>
<div class="item blue"></div>
</div>
<div class="col">
<div class="large item green"></div>
</div>
</div>




Answer

This can be achieved by using flexbox:

  • Add display: flex; to .row. This tells its children to use the flexbox model
  • Add flex-direction: row; to .row as we want the children to align horizontally
  • Add display: flex; to .col. This tells its children to use the flexbox model
  • Add flex-direction: column; to .col as we want the children to align vertically
  • Add flex: 1; to .item to allow it to grow and fill the available space if required
  • A number of styles can be removed from your original version as they are no longer required when using flexbox

.row {
    background:#f99;
    display: flex;
    flex-direction: row;
}
.col {
    background: #999;
    display: flex;
    flex-direction: column;
    margin:0 0 0 12px;
    width:40%;
}
.col:first-child {
    margin:0;
}
.item {
    flex: 1;
    margin: 12px 0 0 0;
    min-height: 80px;
    outline:4px solid black;
    width: 100%;
}
.item:first-child {
    margin:0;
}
.item.red {
    background:#f00;
}
.item.blue {
    background:#0f0;
}
.item.green {
    background:#00f;
}
<div class="row">
    <div class="col">
        <div class="item red"></div>
        <div class="item blue"></div>
    </div>
    <div class="col">
        <div class="large item green"></div>
    </div>
</div>

flexbox support is pretty good, although it isn't supported by older versions of IE. http://caniuse.com/#feat=flexbox

Comments