Nick
Nick

Reputation: 2559

CSS - Automatically set height of container?

Every so often I find myself with this problem and I've never been able to solve it!

Is there any way I can automatically set the height of my container?

Here's a fiddle of an example: http://jsfiddle.net/2x78tcbn/

height: auto; doesn't work in this scenario.

As I say, widths stay the same, but my heights often change, which is why I leave it out - the page loads as expected - other than the container height.

My issue is whenever any content is added beneath the container it shifts up and doesn't render as expected.

Which can be seen here: http://jsfiddle.net/2x78tcbn/1/

Does anybody possibly have a solution for this as it's been baffling me for quite some time!

Really appreciated,

Thanks!

Upvotes: 0

Views: 36

Answers (2)

Diego Farina
Diego Farina

Reputation: 339

Try to set height runtime with jquery and windows size

$('#mainBanner').height($(window).height()-100);
alert($(window).height());

Upvotes: 0

Terry
Terry

Reputation: 66228

That is because you need to clear the float. By definition, floated elements are taken out of the document flow and therefore causes the containing parent's height to collapse. A simple trick is to use overflow: hidden:

#container {
    width: 600px;
    margin: 0 auto;
    overflow: hidden;
}

See fiddle here: http://jsfiddle.net/teddyrised/2x78tcbn/2/

However, in the event that hiding overflowing content is not your desired behavior, you might want to look at other clearfix solutions: http://nicolasgallagher.com/micro-clearfix-hack/

Even better: if cross-browser compatibility is not your main priority, you might want to consider using the latest CSS3 flexbox specification :) http://jsfiddle.net/teddyrised/2x78tcbn/3/

Upvotes: 1

Related Questions