Home >Web Front-end >CSS Tutorial >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
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!