Aspect ratio (natural or specified) transfer across main and cross axes
If a box has a preferred aspect ratio, then Flexbox layout will try to preserve this aspect ratio as much as possible in its calculations.
Images have a natural aspect ratio derived from their source file.
SVG elements have an aspect ratio if they include a viewBox
attribute. For example, viewBox="0 0 200 100"
defines that the svg
element should be 200 pixels wide and 100 pixels tall. That gives it an aspect ratio of 200 to 100, or 2 to 1.
Most other boxes don’t have an aspect ratio by default, but you can specify an aspect ratio with the aspect-ratio
property.
For example, you could have a box representing a card and give it aspect-ratio: 2 / 1
, which means the card should be twice as wide as it is tall.
Flex items will consider their aspect ratio when asking the flex container for a desired flex base size. But they will only do it if they have a definite size in the cross direction.
For example, you could give your flex container a fixed cross size, and let the flex items stretch to fill that size. In that case, this size is known ahead of time and can be used to apply the aspect ratio when requesting the desired flex base size.
But you could have a flex container whose size depends on the size of the flex items. In that case, the flex item doesn’t yet know for sure what size it will have, and can’t apply the aspect ratio.
If your flex item is an image, then the aspect ratio will be used when calculating the automatic minimum size of this image. This is to prevent squishing the image if possible.
If your flex container allows its flex items to wrap, that means the size of the one or more flex lines depends on the size of the flex items. In this case, the flex items don’t know their cross size ahead of time, and aspect ratio can’t be applied.
When the cross size of flex items isn’t known until later, that’s when you can end up with flex items that don’t have their aspect ratio maintained.