2022-09-15

Centering Text in CSS Only When It Fits on One Line

Centering Text in CSS Only When It Fits on One Line

In the vast universe of web development, CSS proves to be a dynamic and versatile player. One scenario where its utility shines involves center-aligning text only when it fits within a single line, but keeping it left-aligned when it extends to multiple lines. This might sound like a tricky feat, but with the right CSS techniques, it's a piece of cake.

Modern Approach

One method to perform this task utilizes the modern capabilities of CSS. Through a simple two-line code block, you can achieve the desired effect. The CSS properties involved are margin-inline: auto and max-inline-size: max-content. Here's what the code looks like:

css
.text {
  margin-inline: auto;
  max-inline-size: max-content;
}

The max-inline-size: max-content ensures the maximum size of the element aligns with the size of its content. The margin-inline: auto behaves akin to margin-left: auto; margin-right: auto;, allowing for the centering of the element.

Alternate Method

Alternatively, you can achieve the same effect using a few CSS properties that have been available for some time now. This approach is helpful if you're working with older versions of CSS or if the modern properties are not supported. The implementation is as follows:

css
.text {
  display: table;
  margin-left: auto;
  margin-right: auto;
  text-align: left; /* Use this if the parent element has text-align: center applied */
}

The mechanism behind this approach includes:

  • Specifying display: table for an element adjusts its width based on its content. Consequently, for short text, the element's width is narrow.
  • The table element is centered horizontally by setting both margin-left and margin-right to auto. This can also be expressed as margin-inline: auto.
  • When text-align: left is set, the text remains left-aligned when it wraps to multiple lines.

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!