简体   繁体   中英

Stretch div to parent's height

I want my content area to stretch to the height of the parent, and I have a fixed height for the title area. I cannot hard-code the height of the content area because in the case I'm working on, the height of the parent area may change.

HTML:

​<div class="parent">
    <div class="title">Title</div>
    <div class="content">
       <p>My Content</p>
    </div>
</div>​

CSS:

.parent{
    width : 500px;
    height: 300px;
    background-color : gray;
    position: absolute;
}

.title{
    height:50px;
    background-color: #94A6E0;
    margin:5px;
}

.content{
    background-color: #8CBF99;
    margin:5px;
}

JSFiddle: http://jsfiddle.net/PGJJv/

There is a way to do it without using fixed heights:

You can set the parent to display: table; and the children to display: table-row . Then the lowest div will take the rest of the height. The only thing is that you need an extra element in between to fake the space between the two elements as border-top or border-bottom don't work on <tr> s. Also you must add padding to the parent in place of margin on the children.

(This is not a real <tr> , it is a sematic div but it is just emulating the behavior of a <tr> .)

HTML:

<div class="parent">
    <div class="title">Title</div>
    <span class="greyLine"></span>
    <div class="content">
        <p>My Content</p>
    </div>
</div>​

CSS:

.parent{
    width : 500px;
    height: 300px;
    background-color : gray;
    position: absolute;
    display: table;
    padding: 5px;
}

.title{
    height:50px;
    background-color: #94A6E0;
    display: table-row;
}

span.greyLine
{
    display: table-row;
    background-color: gray;
    height: 5px;
}

.content{
    background-color: #8CBF99;
    display: table-row;
}​

http://jsfiddle.net/Kyle_/PGJJv/6/

EDIT:

As Dipaks rightly points out, IE7 doesn't support the display: table-row; property.

Maybe you can use the property of a table. Set your parent as a table You can have a fixed height for your title, that you display as a table-row . And your content is the second and last table-row; so it always fit the height of the table.

Here is a fidde example : http://jsfiddle.net/PGJJv/5/

You just have to play with margin and border to recreate exactly your template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM