July 19, 2017

Maintaining aspect ratio in CSS

I had to use a bit of a hack this week to ensure that a box always appeared at a 1:1 aspect ratio. Basically, by doing something like:

.box {
  width: 100%;
  padding-top: 100%;
}

You can force something to display with the same height and width, since the padding percentage is relative to the width.

However, this is not true of flex children, which this box happened to be. Chrome rendered just fine, but FireFox had different behavior, as documented here (the FireFox behavior might actually be more correct, I have no idea). Flex childrens’ percentage-padding is relative to the flex-parent.