Why Doesn\'t `justify-content: center` Center Text in a Flex Container?

Linda Hamilton
Release: 2024-11-02 02:50:30
Original
927 people have browsed it

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>
Copy after login
<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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!