# How To Set Same Height As Width In CSS

## What I wanna build?

![HaHa\~ Four Square Boxes Sit In A Row](https://img.content.cc/a/2022/04/28/15-49-09-964-71caf424f1fd0ae2c8530201e5c1f8e7-0cb88c.png)

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](https://tailwindcss.com/), and the information on class names I used can be found [here](https://tailwindcss.com/docs).

### For the best compatibility

```tsx
<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>
</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

```tsx
<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](https://developer.mozilla.org/en-US/docs/Web/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:

![Browser Compability Of aspect-ratio](https://img.content.cc/a/2022/04/28/16-21-46-068-afd7128636c43c60d21ecfa2ee9a2076-5181df.png)

and you can also check it on [Can I Use](https://caniuse.com/?search=aspect-ratio).

## Reference

1. [Height equal to dynamic width (CSS fluid layout)](https://stackoverflow.com/a/6615994)
2. [Maintain the aspect ratio of a div with CSS](https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://a.b.cr/textbook/frontend/how-to-set-same-height-as-width-in-css.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
