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>
3
Answers
you could use the padding-top propertie
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.
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.