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

How to Maintain Image Aspect Ratio in Flexbox?

DDD
Release: 2024-12-17 19:01:14
Original
477 people have browsed it

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

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;
}
Copy after login
  • align-self: center aligns the image vertically within the container.
  • flex: 0 0 auto prevents the image from stretching or shrinking along the flex axis (i.e., vertically).

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template