How to Justify Text with CSS

Introduction

In this tutorial, you'll learn how to justify text using the text-align property in CSS. This method is useful for creating a neat, professional look in paragraphs or other blocks of text.

Problem Statement

Create a CSS code that:

  • Justifies text within its container using the text-align: justify property.
  • Demonstrates how to apply text justification to a paragraph or block of text.

Example:

  • Input: A paragraph element with the text "Justify Text Example".
  • Output: The text is justified, with even alignment on both sides.

Solution Steps

  1. Use text-align: justify: Apply the text-align property with the value justify to distribute text evenly across the container.
  2. Apply Justification to Block Elements: Use justification on block-level elements like paragraphs for best results.

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Justify Text Example</title>
    <style>
        /* Step 1: Justify text in a paragraph */
        .justify-text {
            text-align: justify;
            border: 1px solid #ccc;
            padding: 10px;
            width: 70%;
            margin: 20px auto;
        }
    </style>
</head>
<body>

    <p class="justify-text">
        This is an example of justified text. The text will be aligned evenly along both the left and right margins, creating a clean, balanced look. Justified text is often used in books, newspapers, and magazines to give a more professional appearance.
    </p>

</body>
</html>

Explanation

Step 1: Use text-align: justify

  • To justify text in a paragraph, use the following CSS:

    .justify-text {
        text-align: justify;
        border: 1px solid #ccc;
        padding: 10px;
        width: 70%;
        margin: 20px auto;
    }
    
  • The text-align: justify property ensures that the text is evenly distributed across the entire width of the container.

Conclusion

Justifying text in CSS is straightforward using the text-align: justify property. This technique helps create balanced, professional-looking text layouts, making it especially useful for articles, reports, and other text-heavy content.

Comments