Kyuubi
Kyuubi

Reputation: 1240

How to use max height and height if you have two divs

I have the following DOM:

<div id="parent" style="height: 200px;">
  <div id="header" style="height: 40px;"></div>
  <div id="content" style="max-height: 100%; overflow-y: auto"></div>
</div>

This leads to content having a height of 200px although I want it to be 160px. Basically the parent div is of variable height and I want the content div to have the height based on it. The header height is fixed.

I cannot use js to solve this, as the actual dom is very convoluted and using JS for it would just make it further complex.

Upvotes: 0

Views: 709

Answers (5)

Danield
Danield

Reputation: 125443

One way to do this is with calc()

#content {
  max-height: calc(100% - 40px);
  overflow-y: auto;
  background:tomato
}

FIDDLE

Alternatively, you could make use of box-sizing to do this:

#content {
  padding-top:40px;
  margin-top:-40px;
  position: relative;
  z-index:-1;
  box-sizing: border-box;
  max-height: 100%;
}

FIDDLE

Upvotes: 1

4dgaurav
4dgaurav

Reputation: 11506

html

<div id="parent">
  <div id="header"></div>
  <div id="content"></div>
</div>

css

#parent {
  background: teal;
  height: 200px;
}

#header {
  background: coral;
  height: 40px;
}

#content {
  background: #eee;
  max-height: calc(100% - 40px); /* 100% - height of header */
  overflow-y: auto
}

DEMO

About calc() and calc() support

Upvotes: 0

Edward
Edward

Reputation: 5238

How about using calc()?

#content {
  height: calc(100% - 40px); 
}

Fiddle - http://jsfiddle.net/upemxmmf/

Upvotes: 1

Paulie_D
Paulie_D

Reputation: 114991

Flexbox can do that.

#parent {
  height: 200px;
  display: flex;
  flex-direction: column
}
#header {
  flex: 0 0 40px;
  background: red;
}
#content {
  flex: 1;
  background: green;
}
<div id="parent">
  <div id="header"></div>
  <div id="content"></div>
</div>

Upvotes: 1

loxxy
loxxy

Reputation: 13151

Pulling the header out of the main flow works?

<div id="parent" style="height: 200px;position:relative;">
  <div id="header" style="height: 40px;position:absolute; top:0;"></div>
  <div id="content" style="padding-top:40px;max-height: 100%; overflow-y: auto"></div>
</div>

Upvotes: 1

Related Questions