How to Align Text to Center with CSS

Introduction

Centering text in CSS is a simple yet frequently used technique to improve the layout of content. The text-align property allows you to align text to the center of its containing element.

In this tutorial, you'll learn how to center text using the text-align property in CSS. This method helps ensure text is properly aligned within its container.

Problem Statement

Create a CSS code that:

  • Centers text within a container using the text-align property.
  • Demonstrates the use of the text-align: center property to align text horizontally.

Example:

  • Input: A paragraph element with the text "Center Aligned Text".
  • Output: The text is horizontally centered within its container.

Solution Steps

  1. Use text-align: center: Apply the text-align property to center text within its parent container.
  2. Ensure Block-Level Container: The parent element must be block-level for the text to be aligned correctly.

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Center Text Example</title>
    <style>
        /* Step 1: Center align text using text-align */
        .center-text {
            text-align: center;
        }

        /* Additional styling to make the text more visible */
        .container {
            border: 1px solid #ccc;
            padding: 20px;
            width: 50%;
            margin: 0 auto;
        }
    </style>
</head>
<body>

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

</body>
</html>

Output

You can play with the above HTML in Online HTML Editor and Compiler. Here is the output of the above HTML page.:

Explanation

Step 1: Use text-align: center

  • To center text within its parent element, use this CSS:
    .center-text {
        text-align: center;
    }
    

Step 2: Block-Level Parent Container

  • The parent element should be a block-level element, such as a div, to ensure the text is centered within it.
.container {
    border: 1px solid #ccc;
    padding: 20px;
    width: 50%;
    margin: 0 auto;
}

Conclusion

Aligning text to the center is straightforward using the text-align: center property in CSS. This method helps improve the layout of text within containers and ensures the content looks visually balanced.

Comments