Big Square

I wanted to have a square on a page that filled up the available space and was centered. But it ended up being more tricky to do that I first thought. Because of all the pain I ending up going through, I wanted to share my final results, so no one else has to go through it again.

Take a look at the example below. It is a long rectangle with a square in the middle. If the rectangle increases in size then the square will automatically expand to fill the available space, and remain in the middle.

Even if the rectangle is resized, so that the width is shorter than the height, the square remains in the middle, but this time vertically.

To see how dynamic the square in the middle moves and stays in the middle, take a look at this full page example. It looks better if you expand it into its own browser page.

To do this requires some CSS and two HTML tags. Here is the HTML parts.

<div class="rectangle">
  <div class="square"></div>
</div>

There is an outer element that is the parent rectangle, and an inner element that will be the square part. Now for the CSS parts.

.rectangle {
  position: relative;
  width: 100%;
  height: 100%;
}

.square {
  background-color: gold;
  aspect-ratio: 1 / 1;
  position: absolute;
  max-height: 100%;
  max-width: 100%;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  margin: auto;
}  

The outer element has the class rectange. It needs to take up all of the parent's width and height. It also needs to have a position value (it doesn't need to be relative).

The inner element has the class square. To make sure it is square, we use the property aspect-ratio and set it to 1 / 1. Having the margin property set to auto makes the square centered. Why having the other properties as they are, making everything work, is a bit of mystery to me.