Skip to content

Default FlexBox Stretching

About 465 wordsAbout 2 min

2023-08-11

Default FlexBox Stretching

In flexbox, the default behavior of flex items is to stretch. If the content of a child item is longer than its siblings, it will cause other items to stretch.

But this is not easy to detect unless we add content to the flex item that is longer than expected.


In this example, we have a component that contains an image, a title, and an introduction.

<div class="food">
  <img class="food__img" src="image/food.jpg" alt="" />
  <div class="food__content">
    <h3>A delicious meal</h3>
    <p><!-- Description goes here.. --></p>
  </div>
</div>
.food {
  display: flex;
}

When the content length is appropriate:

A delicious meal

This is a delicious-looking meal

When the content length is too long:

A delicious meal

This is a delicious-looking meal

This is a delicious-looking meal

This is a delicious-looking meal

This is a delicious-looking meal

This is a delicious-looking meal

This is a delicious-looking meal

This is a delicious-looking meal

It can be found that when the content length is too long, the image is stretched when it exceeds the height of the image.

To solve this problem, we need to override the default stretching behavior.

.food__img {
  align-self: flex-start;
}

When the content length is appropriate:

A serving of food

This is a serving of delicious food

When the content length is too long:

A serving of food

This is a delicious-looking food

This is a delicious-looking food

This is a delicious-looking food

This is a delicious-looking food

This is a delicious-looking food