Designing An Aspect Ratio Unit For CSS

Rachel Andrew says that the CSS Working Group designed an aspect ratio unit at a recent meeting. The idea is to find an elegant solution to those times when we want the height of an element to be calculated in response to the width of the element, or vice versa.

Say, for example, we have a grid layout with a row of elements that should maintain a square (1:1) ratio. There are a few existing, but less-than-ideal ways we can go:

  • Define one explicit dimension. If we define the height of the items in the grid but use an intrinsic value on the template columns (e.g. auto-fill), then we no longer know the width of the element as the container responds to the browser viewport. The elements will grow and squish but never maintain that perfect square.
  • Define explicit dimensions. Sure, we can tell an element to be 200px wide and 200px tall, but what happens when more content is added to an item than there is space? Now we have an overflow problem.
  • Use the padding hack. The block-level (top-to-bottom) padding percentage of an element is calculated by the element’s inline width and we can use that to calculate height. But, as Rachel suggests, it’s totally un-intuitive and tough to maintain.

Chris wrote up a full rundown of possible ways to maintain aspect ratio, but none of them are as elegant as CSS Working Group’s proposed solution:

.box {
  width: 400px;
  height: auto;
  aspect-ratio: 1/1;
}

See that? An aspect-ratio property with an aspect ratio unit would calculate the height of the element based on the value of the width property.

Or, in the case of a grid layout where the columns are set to auto-fill:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}

.item {
  aspect-ratio: 1/1;
}

Very cool! But where does the proposal go from here? The aspect-ratio is included in the rough draft of the CSS Sizing 4 specification. Create an issue in the CSSWG GitHub repo if you have ideas or suggestions. Or, as Rachel suggests, comment on her Smashing Magazine post or even write up your own post and send it along. This is a great chance to add your voice to a possible new feature.

Direct Link to ArticlePermalink

The post Designing An Aspect Ratio Unit For CSS appeared first on CSS-Tricks.

Related Post