Make a truly responsive square with CSS
A new css property aspect-ratio
finally allows for a width and height responsive square without any JavaScript.
Browser Compatibility is as of April 2021 still limited to Chrome and Edge.
Here’s how it works!
Create two objects. A container and a square. Give the square an aspect ratio equal to one, and a width and max height of 100% of the parent container.
.square {
aspect-ratio: 1 / 1;
width: 100%;
max-height: 100%;
}
Optionally you can center the square within the parent, with the old position and transform trick…
I have not found a way to center the square, the more convenient way, by using Flexbox or Grid (yet?).
… as well as making the container resizable with the resize
property from the textarea
HTML object.
.resizable {
resize: both;
overflow: hidden; position: relative;
}.square {
aspect-ratio: 1 / 1;
max-height: 100%;
width: 100%;
// Centering square within resizable container
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); // Centering the content of square
display: grid;
place-content: center;
}
Here’s an example to play around with!