Text not centered with justify-content: center

The HTML structure of a flex container has three levels:

  • the container
  • the item
  • the content

Each level represents a separate, independent element.

The justify-content property, which is set on flex containers, controls flex items. It has no direct control over the children of the item (the text, in this case).

When you set justify-content: center on a row-direction container the item shrinks to the content width (i.e., shrink-to-fit) and is horizontally centered. The content, being inside the item, goes along for the ride.

Everything is centered nicely, when the content is narrower than the flex container.

On the other hand, when the content is wider than the flex container, the flex item can no longer be centered. In fact, the item cannot be aligned at all (start, end, center) because there is no free space – the item is consuming the full width of the container.

In such cases, the text can wrap. But justify-content: center doesn’t apply to the text. It never did. The text was always subject to the default text-align: start (left in LTR / right in RTL).

Therefore, to center the text directly, add text-align: center to the flex item (or the flex container, it doesn’t really matter due to inheritance).

article {
  display: flex;
  align-items: center;
  justify-content: center;
}

.center {
  text-align: center;
}

/* demo styles only */
article {
  width: 100px;
  height: 100px;
  margin: 10px;  
  background-color: lightgreen;
}
<article>
  <p>some long text here</p>
</article>

<article>
  <p class="center">some long text here</p>
</article>

Leave a Comment