How To Set Same Height As Width In CSS
I am pretty sure this is a frequently asked question from frontend beginners like me...
Last updated
I am pretty sure this is a frequently asked question from frontend beginners like me...
Last updated
I want to create square boxes, however, it really bothered me for a while.
The following examples were created in React and based on Tailwind CSS, and the information on class names I used can be found here.
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.
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.