Blackbam
Blackbam

Reputation: 19366

Percentage height within auto height parent div?

How do you get a child div to be 120% the height of a parent, when the parent height is unspecified (auto)?

When the parent has a specified height it works:

#bar {
  background-color:rgba(120,0,0,0.5);
  height:120px;
}

#child {
  background-color:rgba(0,120,0,0.5);
  height:120%;
}
<div id="bar">
  <div id="child">
    Lorem<br/>
    ipsum<br/>
    dolor<br/>
    sit<br/>
    amet.
  </div>
</div>

When the parent height is auto (unspecified) it fails:

#bar {
  background-color:rgba(120,0,0,0.5);
}

#child {
  background-color:rgba(0,120,0,0.5);
  height:120%;
}
<div id="bar">
  <div id="child">
    Lorem<br/>
    ipsum<br/>
    dolor<br/>
    sit<br/>
    amet.
  </div>
</div>

Upvotes: 2

Views: 767

Answers (2)

Mario Rawady
Mario Rawady

Reputation: 871

Use :before instead on a child div.

#bar {
  position: relative;
  display: block;
  background-color:rgba(120,0,0,0.5);
}

#bar:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 120%;
  background-color:rgba(0,120,0,0.5);

}

#child {
  position:relative;
  z-index:10;
}
<div id="bar">
  <div id="child">
    Lorem<br/>
    ipsum<br/>
    dolor<br/>
    sit<br/>
    amet.
 </div>
</div>

Upvotes: 2

James Donnelly
James Donnelly

Reputation: 128791

Logically this will not work because the height of your height: auto element is determined by the height of its children. If the height of the child relied on the automatic height of the parent you'd end up with a circular dependency. Because of this problem, children of auto-height elements cannot have their height rely on that element - percentage units will therefore be ignored.

You'll need to take a step back and come up with a different approach to whatever it is you're ultimately trying to achieve.

Upvotes: 5

Related Questions