pleasedontbelong
pleasedontbelong

Reputation: 20102

CSS height 100% when inner childs have float

I have a basic structure

<div class="container">
    <div class="sidebar">
    </div>
    <div class="content">
    </div>
    <div style="clear:both;"></div>
</div>

where .sidebar and .content have float: left

I've seen too many answers on S.O. and they all work ONLY IF .content is not bigger than the screen itself. To illustrate my problem i have this two examples

http://jsfiddle.net/pleasedontbelong/h35vc/2/ (small content) http://jsfiddle.net/pleasedontbelong/56C9v/1/ (big content)

as you can see, when the .content div is too big the height:100% on the container doesn't work anymore.

In both cases, the gray div should be 100% height. My guess is that the browser calculates the window height before floating the elements.

Is it possible to solve this using only CSS? (i could do it with JS but it just seems too dirty)

Upvotes: 0

Views: 1032

Answers (4)

Michael Theriot
Michael Theriot

Reputation: 1022

If I understand you correctly, you want the container to always be 100% of the height of the document and the floats to also stretch down but not increase the height of the container.

Margins on the body make it exceed 100% height, so to eliminate that...

html, body {
  height: 100%;
  margin: 0;
}

Your container has padding which will exceed 100% height, so we use the new border-box...

.container{
  background-color: #999;
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
}

Then set the floats to 100% height and handle text overflowing with a scroll bar...

.sidebar, .content {
  height: 100%;
  overflow: auto;
}

I think this is what you are trying to achieve? http://jsfiddle.net/56C9v/10/

Upvotes: 0

Kevin Lynch
Kevin Lynch

Reputation: 24703

Remove the height attribute

.container{
    background-color: #999;
    padding: 20px;
    //no height declared
}

DEMO http://jsfiddle.net/56C9v/7/

If you want the container to always occupy 100% then set min-height: 100% eg

.container{
        background-color: #999;
        padding: 20px;
        min-height: 100%;
    }

Upvotes: 2

j08691
j08691

Reputation: 207891

Get rid of the heights and put overflow:auto on your container.

jsFiddle example (large)

jsFiddle example (small)

Upvotes: 0

Adam Plocher
Adam Plocher

Reputation: 14233

If I understand you correctly, you don't want the container/content to ever go beyond 100% of the screen height.

You can accomplish this by adding: overflow:hidden; to your container stylesheet.

For more information about the overflow property, see: https://developer.mozilla.org/en-US/docs/Web/CSS/overflow

Upvotes: 0

Related Questions