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
Release: 2024-12-07 08:28:13
Original
836 people have browsed it

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>
Copy after login
.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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template