Home >Web Front-end >CSS Tutorial >How to Preserve Image Aspect Ratio in CSS Flexbox?
Maintaining Image Aspect Ratio in Flexbox
Maintaining image proportions when resizing its height can be a challenge in the CSS flexbox model. However, there are several methods available to achieve this.
Object-Fit Property
One approach is to use the object-fit property on the image. By setting object-fit: contain, the image will be scaled to fit within its target container while preserving its aspect ratio.
Flex-Specific Rules
Another option is to employ flex-specific rules:
Example
Here's an example that demonstrates both methods:
<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; height: 200px; } .slider img { margin: 0 5px; object-fit: contain; } /* Alternative Flex-Specific Rules */ .slider img { align-self: center; flex: 0 0 auto; }
This method should effectively preserve image aspect ratios, even when adjusting their height.
The above is the detailed content of How to Preserve Image Aspect Ratio in CSS Flexbox?. For more information, please follow other related articles on the PHP Chinese website!