Home >Web Front-end >CSS Tutorial >Why Doesn\'t `justify-content: center` Center Text When It Wraps in a Flex Container?
Text Not Centered with justify-content: center
This issue arises when the content within a flex container becomes excessively long, resulting in wrapping. While the content is horizontally centered with justify-content: center, the alignment is disrupted during wrapping.
Understanding the Three Levels in Flexbox
A flex container structure consists of three levels:
Each level represents an independent element.
Justification in Flex Containers
justify-content controls the alignment of flex items within the container, but it does not directly influence the children of the item (in this case, the text).
When the flex container's width exceeds the content's width, the flex item shrinks to fit the content (shrink-to-fit) and is centered horizontally. The content within the item automatically follows this alignment.
Alignment When Content Exceeds Flex Container
However, when the content becomes wider than the flex container, the flex item can no longer align. Since the item occupies the entire container width, there is insufficient free space for alignment.
Text Alignment
Despite the misalignment, text-align: center was never applied to the text by default. To directly center it, text-align: center must be explicitly added to either the flex item or the flex container.
Code Example
<code class="css">article { display: flex; align-items: center; justify-content: center; } .center { text-align: center; }</code>
<code class="html"><article> <p>some long text here</p> </article> <article> <p class="center">some long text here</p> </article></code>
The above is the detailed content of Why Doesn\'t `justify-content: center` Center Text When It Wraps in a Flex Container?. For more information, please follow other related articles on the PHP Chinese website!