Home >Web Front-end >CSS Tutorial >How to Prevent Flex Items from Stretching to Container Width?

How to Prevent Flex Items from Stretching to Container Width?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 09:13:08332browse

How to Prevent Flex Items from Stretching to Container Width?

How to Force Flex Items to Fit Content, Not Container Width

In flex layouts, elements naturally stretch to fill the width of their parent container. This can be undesirable when you want child elements to wrap their contents only. Here's how to enforce this behavior:

Solution Using align-items/align-self

Set align-items: flex-start on the container, or align-self: flex-start on the flex items. This overrides the default align-items: stretch, which causes items to expand to fill the container's horizontal space when the flex-direction is column.

How it Works

By setting align-items: flex-start, you force items to align themselves to the starting edge of the container. Since the column direction is set, the starting edge is the left edge. This forces items to stay as wide as their content only.

Example:

.container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
a {
  padding: 10px 40px;
  background: pink;
}

Related Concepts

  • Cross Axis: The axis perpendicular to the primary layout axis (horizontally in column layouts).
  • align-items: Aligns flex items along the cross axis.
  • align-self: Similar to align-items, but specific to individual flex items.

The above is the detailed content of How to Prevent Flex Items from Stretching to Container Width?. 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