How To Set Same Height As Width In CSS

I am pretty sure this is a frequently asked question from frontend beginners like me...

What I wanna build?

I want to create square boxes, however, it really bothered me for a while.

Let's go straight to the code!

The following examples were created in React and based on Tailwind CSS, and the information on class names I used can be found here.

For the best compatibility

<div className="inline-block relative w-1/4">
  <div className="mt-[100%]"></div>
  <div className="absolute top-0 bottom-0 left-0 right-0 border-2"></div>

The key to success is a magic mt-[100%]. It works because when using margin/padding-top/bottom with percentage, the value is determined according to the width of the containing element which is w-1/4 for width: 25% in my code. Essentially, we have a situation where "vertical" properties can be sized with respect to a "horizontal" property. This isn't an exploit or a hack, because this is how the CSS specification is defined.

For modern browsers

<div className="relative w-1/4 aspect-[1] border-2"></div>

Yes! You can actually solve this century problem with a simple aspect-[1], which repesents aspect-radio: 1; in CSS.

The aspect-ratio CSS property sets a preferred aspect ratio for the box, which will be used in the calculation of auto sizes and some other layout functions.

Thanks to modern browsers, this solution is elegant and easy to understand, and here is the browser compatibility:

and you can also check it on Can I Use.


Last updated