How to Align Text in HTML – Text-align, Center, and Justified Example

web
#html #css

In HTML, there are several ways to align text, and in this tutorial, we’ll explore the text-align property along with centering and justifying text with practical code examples.

1. The text-align Property

The text-align property is used to control the alignment of text within an HTML element. It can be applied to block-level elements like paragraphs (<p>) or headers (<h1>, <h2>, etc.) as well as inline elements within block-level containers. The property accepts four main values:

  • left: Aligns the text to the left edge.
  • right: Aligns the text to the right edge.
  • center: Centers the text horizontally.
  • justify: Adjusts the spacing between words to create even margins on both sides.

Here’s an example of using the text-align property:

<!DOCTYPE html>
<html>
<head>
<style>
    .text-container {
        text-align: center;
    }
</style>
</head>
<body>

<div class="text-container">
    <p>This is centered text using the text-align property.</p>
</div>

</body>
</html>

2. Centering Text

Centering text is a common styling technique to draw attention to important content. You can center text both horizontally and vertically within a container using various methods. Here’s how you can center text horizontally:

Method 1: text-align Property

As shown in the previous example, the text-align: center; property can be applied to a container to center the contained text.

Method 2: Flexbox

Flexbox is a powerful layout technique that allows you to create flexible and responsive designs. To center text both horizontally and vertically within a container, you can use the following approach:

<!DOCTYPE html>
<html>
<head>
<style>
    .flex-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 300px; /* Adjust as needed */
    }
</style>
</head>
<body>

<div class="flex-container">
    <p>This text is centered using Flexbox.</p>
</div>

</body>
</html>

3. Justifying Text

Justified text provides a clean and polished appearance by evenly adjusting the spacing between words. It creates a neat alignment on both the left and right sides. Here’s how you can justify text:

<!DOCTYPE html>
<html>
<head>
<style>
    .justified-text {
        text-align: justify;
    }
</style>
</head>
<body>

<p class="justified-text">
    This is an example of justified text. It creates even spacing between words to align both left and right sides.
</p>

</body>
</html>

Conclusion

Text alignment is a fundamental aspect of web design that significantly influences the presentation and readability of your content. In this article you learned how to align textusing the text-align property along with centering and justifying text.