Start Coding

CSS Text Alignment

CSS text alignment is a fundamental aspect of web design that allows developers to control the horizontal positioning of text within elements. It plays a crucial role in creating visually appealing and readable layouts.

The text-align Property

The primary method for aligning text in CSS is the text-align property. This versatile property can be applied to block-level elements and offers four main values:

  • left: Aligns text to the left (default)
  • right: Aligns text to the right
  • center: Centers the text
  • justify: Spreads text evenly, creating flush left and right edges

Example Usage


.left-aligned {
    text-align: left;
}

.right-aligned {
    text-align: right;
}

.centered {
    text-align: center;
}

.justified {
    text-align: justify;
}
    

Aligning Last Line of Justified Text

When using justified text, you can control the alignment of the last line using the text-align-last property. This is particularly useful for creating polished paragraph endings.


p {
    text-align: justify;
    text-align-last: right;
}
    

Vertical Alignment

While text-align handles horizontal alignment, vertical alignment often requires different techniques. For inline elements, you can use the vertical-align property. For block-level elements, consider using CSS Flexbox or CSS Grid for more complex layouts.

Considerations and Best Practices

  • Use left alignment for most body text to improve readability.
  • Center alignment works well for headings and short blocks of text.
  • Justified text can look professional but may create uneven spacing between words.
  • Consider the impact of text alignment on responsive designs and readability across devices.
  • Use text-align: inherit; to reset alignment to the parent element's value.

Browser Support and Compatibility

The text-align property has excellent browser support across all modern browsers. However, some advanced properties like text-align-last may have limited support in older browsers. Always test your designs across different platforms to ensure consistency.

Related Concepts

To further enhance your text styling skills, explore these related CSS concepts:

By mastering CSS text alignment along with these related properties, you'll have the tools to create visually appealing and well-structured text layouts for your web projects.