Home >Web Front-end >CSS Tutorial >How to Preserve Image Aspect Ratio in CSS Flexbox?

How to Preserve Image Aspect Ratio in CSS Flexbox?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 08:28:13786browse

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:

  • Set align-self: center to vertically center the image within its parent container.
  • Set flex: 0 0 auto to make the image's width and height flexible, allowing it to shrink or expand as needed.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn