4

I have a div and I have set its width to 100%

So the div can resize as its parent element or window resizes.

However, I want the div to have a 50% height, what CSS should I write? (or any other percentage, not just 50%)

It seems that 50% is definitely the wrong way to go.

I can use JavaScript to do this but is there any pure CSS way?

#out {
  border:1px solid #f00;
  position:relative;
  width:100%;
  height:50%;
}
<div id="out">
stuff<br>
stuff<br>
</div>
AGamePlayer
  • 7,404
  • 19
  • 62
  • 119

1 Answers1

2

As any percentages assigned to margin and padding are calculated based on width, you can use that to maintain the aspect ratio:

#out {
  border: 1px solid #f00;
  padding: 25% 0;
  position: relative;
  width: 100%;
}
<div id="out">
  stuff<br> stuff
  <br>
</div>

The problem with that, though, is that your content further increases the height. For that to be solved, wrap the content in another container, which you give position: absolute:

#out {
  border: 1px solid #f00;
  padding: 25% 0;
  position: relative;
  width: 100%;
}

.inner {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
<div id="out">
  <div class="inner">
    stuff<br> stuff
    <br>
  </div>
</div>
connexo
  • 53,704
  • 14
  • 91
  • 128