tkbx
tkbx

Reputation: 16275

Div fill height of parent div?

I'm trying to get a div to fill the remaining height of a div. Here's my HTML and CSS:

CSS:

* {
    padding: 0px;
    margin: 0px;
}
#container {
    margin: 85px auto 0px auto;
    background: #444444;
    min-height: 500px;
    width: 900px;
}
#topbar {
    width: 900px;
    height: 85px;
    background: #555555;
}
#leftbar {
    width: 250px;
    height: 100%;   
    background: #666666;
}

HTML:

<div id="container">
    <div id="topbar">
    </div>
    <div id="leftbar">
    </div>
</div>

I expected leftbar to fill the height between the bottom of topbar and the bottom of container, but it's scretching container so that leftbar is 100% of the page height.

Upvotes: 0

Views: 363

Answers (4)

robertp
robertp

Reputation: 3652

You can stretch the leftbar with absolute positioning and setting the top/bottom values:

* {
    padding: 0px;
    margin: 0px;
}
#container {
    position: relative;
    margin: 85px auto 0px auto;
    background: #444444;
    min-height: 500px;
    width: 900px;
}
#topbar {
    width: 900px;
    height: 85px;
    background: #555555;
}
#leftbar {
    position: absolute;
    top: 85px;
    bottom: 0;
    width: 250px;
    background: red;
}

Fiddle: http://jsfiddle.net/robertp/CQ7pf/

Upvotes: 1

ryanpf
ryanpf

Reputation: 136

So leftbar should be container's height minus topbar's height. Since container and topbar have hard-coded height values, it follows that leftbar will have to be hard-coded also. It's not the prettiest thing in the world but it's simpler than the alternative, JavaScript.

If container is 500px in height, subtract the height of topbar (85) and container's margin (85) to arrive at a height of 330px. Since container uses min-height, use min-height for leftbar also to allow it to stretch the container if need be. You should also change leftbar's position to relative to render the height of container correctly.

Bottom line:

#leftbar {
position: relative;
min-height: 330px;
}

Upvotes: 0

Kevin Lynch
Kevin Lynch

Reputation: 24703

Set your left bar to position: relative;

Upvotes: 0

Josh
Josh

Reputation: 760

Try adding this to container:

position: relative;

and then add this to leftbar:

position: absolute;
top: 0;
bottom: 0;

Upvotes: 1

Related Questions