0

I would like to assign to a div's height the 80% of the parent width.

Ideally something like:

foo {
    height: 80%width;
}
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
room13
  • 883
  • 2
  • 10
  • 26
  • 1
    note for the duplicate: a block element will by default have its width equal to parent width (if we omit any margin/padding/border) so the question is to make height based on width for the same element which is maitaining an aspect ratio – Temani Afif Jan 16 '20 at 22:51

2 Answers2

1

It's funny you should ask this because the default browser behavior, before flexbox was just that, height % units were based off the width of the parent block-level element by default.

We could work around it as per the following example & use padding-bottom ( %-units of which will be based off the parent element's width) with position:relative & then absolute-position a container inside of that to accomplish the layout logic you've asked for

<div style="width:300px; height:250px; border: 1px solid #ccc">
  <div style="position: relative; padding-bottom: 50%; background: #ccc">
    <div style="position: absolute; top: 0; right: 0; bottom: 0; left: 0; border: 1px solid #000">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
    </div>
  </div>
</div>

& here's an example with the css extracted from the html

.outter {
  width:300px;
  height:250px;
  border: 1px solid #ccc;
}
.inner {
  position: relative;
  padding-bottom: 50%;
  background: #ccc;
}
.inner-inner {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  border: 1px solid #000
}
   <div class="outter">
      <div class="inner">
        <div class="inner-inner">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
        </div>
      </div>
   </div>
admcfajn
  • 2,013
  • 3
  • 24
  • 32
0

Here is another way, although I prefer admcfajn's way of using the padding-height. This uses the img tags ability to autoscale to force the container height to be 80% of the width. The png in the img is a 5x4 transparent image which is autoscaled up to 100% width, and 80% height.

.container {
  position:relative;
}
.container > img {
  width: 100%;
  height: auto;
  border: none;
}
.container > .content {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  outline: 1px solid red;
}
<div class='container' style='width:300px'>
  <img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAECAYAAABGM/VAAAAAD0lEQVQYV2NkwAIYKRMEAAEmAAUCYu5+AAAAAElFTkSuQmCC' />
  <div class='content'>
  Boo
  </div>
</div>
Robert McKee
  • 21,305
  • 1
  • 43
  • 57