Squares
sometimes you need to determine the height of an element based on its width. This is a common use case for images, but it can be used for any element.
<div style={{ width: "100px", position: "relative" }}>
<div
style={{
paddingBottom: "100%",
position: "relative",
}}
>
<img
src="https://via.placeholder.com/150"
style={{ position: "absolute", width: "100%", height: "100%" }}
/>
</div>
</div>
Explanation
The outer div is the container, and the inner div is the aspect ratio container. The aspect ratio container is a square because the padding-bottom
is set to 100%
. The image is absolutely positioned inside the aspect ratio container and set to width: 100%
and height: 100%
. This makes the image fill the aspect ratio container while maintaining the aspect ratio of the image.