0

Let's say we have responsive rectangle. I need to fit square element into rectangle and it should be 100% of its height. How could you do it with CSS only (no SVG and JS, no fixed sizes)? In other words: make child element's width equal to parent element's height?

It's easily done with SVG as child element using viewbox property but I need pure CSS solution.

<div style="width: 95vw; height: 100%; border: 2px solid #f00">
  <div style="border: 2px solid #0f0">I'm 100% of parent's height but also I'm not square</div>
</div>
  • 1
    Please revise the demo above so it shows the problem. Maybe put the text in the div instead of in a title. See [ask] and take the [tour] for tips. Note that the body element has no height, so 100% height doesn't get you much here. – isherwood Apr 11 '23 at 20:50

3 Answers3

1

You can use the aspect-ratio property to ensure that the inner element is always 1:1, or square. You will have to define some height on your parent element though.

* {
  box-sizing: border-box;
}

.parent {
  width: 95vw;
  height: 100px;
  border: 2px solid #f00;
}

.child {
  aspect-ratio: 1/1;
  height: 100%;
  border: 2px solid #0f0;
}
<div class="parent">
  <div class="child">I'm 100% of parent's height and square</div>
</div>
David
  • 311
  • 1
  • 2
  • 12
  • Nice. Any idea how to achieve that without aspetc-ratio? This feature was added to browsers couple years ago. – user21620928 Apr 11 '23 at 21:36
  • Support for aspect-ratio is actually quite good now that IE11 is dead: https://caniuse.com/?search=aspect-ratio However I'm not sure there's an alternative pure CSS solution. You would have to do something hacky like use an invisible image to maintain the ratio like in the top voted answer in this question: https://stackoverflow.com/questions/26438388/maintain-div-aspect-ratio-according-to-height At that point, you'd be better off using javascript to get the parent height and set the width accordingly – David Apr 11 '23 at 21:52
1

Modern browsers have an aspect-ratio property.

If you give the child 100% of the parents height then it’s width will be the same.

Note that in your snippet there was no real height to the parent so I’ve, arbitrarily, give it a height just for demo. In a real situation I expect the parents setting of 100% would have something to set itself to.

<div style="width: 95vw; height: 300px; border: 2px solid #f00">
  <div style="border: 2px solid #0f0; aspect-ratio: 1 / 1; height: 100%;">I'm 100% of parent's height but also I'm not square</div>
   Get </div>
A Haworth
  • 30,908
  • 4
  • 11
  • 14
-1

you could use the padding-top propertie

<div class="rectangle">
  <div class="square"></div>
</div>

.square {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%; 
  height: 100%; 
  background-color: red;
}

.rectangle {
  position: relative;
  width: 0;
  height: 100%;
  padding-top: 100%; 
}



InvstIA
  • 84
  • 4