Home >Web Front-end >CSS Tutorial >How to Stop Flex Items from Stretching in Flexbox?

How to Stop Flex Items from Stretching in Flexbox?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-17 08:40:03725browse

How to Stop Flex Items from Stretching in Flexbox?

Preventing Flex Items from Stretching

When using the Flexbox layout, it's possible for flex items to stretch and fill the available space in their container. However, there are situations when you may want to prevent this from happening.

Why Can Flex Items Stretch?

By default, flex items will stretch along the primary axis of their container, which is typically either horizontal (row) or vertical (column). This is because the flex property is set to 1 by default, which indicates that the item should be flexible and expand to fill any available space.

Preventing Flex Item Stretching

To prevent a flex item from stretching, you can override the default flex value by setting it to 0. This will cause the item to shrink to fit its content, preventing it from taking up more space than necessary.

Example

Consider the following example:

div {
  display: flex;
  height: 200px;
  background: tan;
}
span {
  background: red;
}
<div>
  <span>This is some text.</span>
</div>

In this example, the flex item (span) stretches to fill the full height of its container. To prevent this, add the following style to the div element:

align-items: flex-start;

This aligns the flex items along the start of their container, preventing them from stretching to fill the full height.

The above is the detailed content of How to Stop Flex Items from Stretching in 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