Set Text Alignment Working with CSS

The CSS text-align property is used to horizontally align text content within an element. It controls the alignment of text and inline elements inside block-level containers.

Syntax

selector {
    text-align: value;
}

Possible Values

Value Description
left Aligns text to the left (default for most languages)
right Aligns text to the right
center Centers the text
justify Stretches text to align both left and right edges

Example 1: Basic Text Alignment

The following example demonstrates different text alignment options −

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        width: 300px;
        border: 2px solid #333;
        padding: 20px;
        margin: 10px 0;
    }
    .left-align {
        text-align: left;
    }
    .center-align {
        text-align: center;
    }
    .right-align {
        text-align: right;
    }
    .justify-align {
        text-align: justify;
    }
</style>
</head>
<body>
    <div class="container left-align">
        <p>This text is aligned to the left.</p>
    </div>
    <div class="container center-align">
        <p>This text is centered.</p>
    </div>
    <div class="container right-align">
        <p>This text is aligned to the right.</p>
    </div>
    <div class="container justify-align">
        <p>This text is justified, which means it stretches to align both left and right edges of the container.</p>
    </div>
</body>
</html>
Four bordered containers appear with text aligned differently:
- First box: Text aligned to the left
- Second box: Text centered
- Third box: Text aligned to the right  
- Fourth box: Text justified with even spacing

Example 2: Table Cell Alignment

This example shows how to align text within table cells −

<!DOCTYPE html>
<html>
<head>
<style>
    table {
        width: 100%;
        border-collapse: collapse;
    }
    td {
        padding: 15px;
        border: 1px solid #ddd;
        background-color: #f9f9f9;
    }
    .left-cell {
        text-align: left;
    }
    .center-cell {
        text-align: center;
    }
    .right-cell {
        text-align: right;
    }
</style>
</head>
<body>
    <table>
        <tr>
            <td class="left-cell">Left aligned cell</td>
            <td class="center-cell">Center aligned cell</td>
            <td class="right-cell">Right aligned cell</td>
        </tr>
    </table>
</body>
</html>
A table with three cells showing different text alignments:
- Left cell: text aligned to the left
- Center cell: text centered
- Right cell: text aligned to the right

Conclusion

The text-align property is essential for controlling horizontal text positioning. Use left, right, center, or justify based on your design needs and content requirements.

Updated on: 2026-03-15T14:10:58+05:30

710 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements