Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fitting two <div> inside document height

Tags:

css

I'm trying to layout some html <div> elements to be like in the picture:

layout

Problem here is #container height. Setting it a fixed value or a percentage it will either leave empty space at the bottom or will bypass html height.

I tried setting it to 90% (10% is for #title) but it is not accurate deppending on client height; What I have so far is this:

body, html{ height: 100%; margin: 0px}
#container{ height: 90%; overflow: scroll;}

Considering #title height may also vary, is it possible to use css to fit #title and #container inside the html?

like image 800
Azevedo Avatar asked Jan 30 '26 17:01

Azevedo


1 Answers

Two options, flex display or the CSS calc operator.

You could probably more easily solve this if you know what your header is going to be in any given circumstance. In that case, you use calc like so:

header {
  height: 190px; /* Or whatever you'd like it to be */
}
.container {
  height: calc(100% - 190px); /* Where 190px is whatever height the header is set to */
  overflow: auto; /* Or scroll, if you want the scrollbar always visible */
}

In the less ideal case, you need to use flex for a flexbox display.

That would look something like this:

body {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
}
header {
  height: 10%; /* Or whatever */
  flex: none;
}
.container {
  align-self: flex-end;
  flex: 1 0 100%;
}

Let's walk through that one. It's missing most of the vendor-specific stuff you need if you want broader support, but flex displays are supported in almost all major browsers now.

First we set body to have display: flex which informs the browser that this is a flex layout. We also set the flex-direction and flex-wrap. These properties should be fairly self-explanatory.

Second we set the header to a fixed display. We do that via height: 10% but the value could be whatever you want. The flex: none tells the browser this element is immutable in context of the flex. If you think of the display as a river, this is a stone sitting in the middle of it.

Third we set the container to align itself at the bottom of the page using align-self: flex-end. This is so that it's always going to be at the bottom, regardless of other elements on the page. This isn't super important as we're not wrapping (set in the body element) but we're covering bases here. The important part is flex: 1 0 100%. Put simply this is saying:

  1. Grow to a factor of 1 (100%) in relation to all other flexed elements (none in this simple case).
  2. Don't shrink at all (shrink to a factor of 0).
  3. Set a default height of 100% (or as close to it as possible).

Hope that helps!

like image 93
Josh Burgess Avatar answered Feb 01 '26 06:02

Josh Burgess



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!