Maintain image aspect ratio when changing height
Your image will keep its aspect ratio by using the handy height
and width
properties in your CSS. The CSS snippet ensures that the height is fixed and width is auto-adjusted.
Using object-fit
to keep things shapely
In CSS, object-fit: contain;
allows the image to scale while keeping its aspect ratio. It stops your image from stretching out like an accordion (in a bad way):
The dance of the flex
-boxes
Flexing with aspect ratio
flex
properties combined with object-fit
can maintain aspect ratio:
Wrapping images nicely
Wrapping images within a div
or span
offers awesome control within a flex container:
Addressing browser-affairs
Handling different browser quirks
Unsurprisingly, browser-specific bugs dance around. Flexbox has a knack to make ordinary people pull their hair out due to sizing bugs. The "Implied Minimum Size of Flex Items" is a topic worth reading and Mozilla Developer Network is the Wikipedia of bug reports and solutions.
Testing it on different browsers
Ensure that your images are well-behaved when they meet different browsers:
Feel free to take a peek at this practical example over here: http://jsfiddle.net/ykw3sfjd/
The CSS survival kit for aspect ratios
Giving display: table;
a fair chance
If flexbox has been showing attitude, display: table;
can simplify your life while keeping image aspect ratios intact:
Checking your webpage's health
Also, monitor your web performance. Using too many high-resource properties could compel users to click the dreadful back button. Google Lighthouse can come to your rescue for identifying performance issues.
Was this article helpful?