Text not centered with justify-content: center

前端 未结 1 1074
灰色年华
灰色年华 2020-11-27 22:54

I\'ve got a div with display: flex. Its content is centered horizontally and vertically.

When content is too long in the div, the content wraps. But the

相关标签:
1条回答
  • 2020-11-27 23:18

    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>

    0 讨论(0)
提交回复
热议问题