Home >Web Front-end >CSS Tutorial >Why Doesn\'t `justify-content: center` Center Text in a Flex Container?
Non-centered Text with justify-content: center
In a flex container, the justify-content property centers flex items horizontally, but it has no direct control over the text within those items. When the text wraps within the item, it retains its default text-align: start value, resulting in non-centered text.
The flex container, flex items, and text represent three distinct levels in the HTML structure. justify-content affects flex items, not the text contained within them.
If the flex item fills the width of its container, it cannot be centered, hence the misaligned text upon wrapping.
To center the text directly, assign text-align: center to the flex item or container through inheritance.
Example
<code class="css">.box { width: 100px; height: 100px; background-color: lightgreen; margin: 10px; display: flex; align-items: center; justify-content: center; } .with-align p { text-align: center; }</code>
<code class="html"><div class="box"> <p>some long text here</p> </div> <div class="box with-align"> <p>some long text here</p> </div></code>
The above is the detailed content of Why Doesn\'t `justify-content: center` Center Text in a Flex Container?. For more information, please follow other related articles on the PHP Chinese website!