Home >Web Front-end >CSS Tutorial >How to Maintain Image Aspect Ratio in Flexbox?
Maintaining Image Aspect Ratio in Flexbox
In a flexbox layout, images tend to stretch or shrink disproportionately to fill the width of the container. To maintain the aspect ratio while adjusting the image height, consider the following solutions:
Option 1: object-fit
Add the object-fit property to the image:
img { object-fit: contain; }
This ensures that the image retains its dimensions while fitting within the container.
Option 2: Flexbox Rules
Use the following flexbox properties on the image:
img { align-self: center; flex: 0 0 auto; }
Live Example:
<div class="slider"> <img src="http://www.placebacon.net/400/300" alt="Bacn"> <img src="http://www.placebacon.net/400/300" alt="Bacn"> <img src="http://www.placebacon.net/400/300" alt="Bacn"> <img src="http://www.placebacon.net/400/300" alt="Bacn"> </div>
.slider { display: flex; } .slider img { margin: 0 5px; } /* Option 1: object-fit */ .img-contain { object-fit: contain; } /* Option 2: Flexbox Rules */ .img-flex { align-self: center; flex: 0 0 auto; }
The above is the detailed content of How to Maintain Image Aspect Ratio in Flexbox?. For more information, please follow other related articles on the PHP Chinese website!