0
0
CSSmarkup~5 mins

Text alignment in CSS

Choose your learning style9 modes available
Introduction
Text alignment helps you control how text lines up inside a box or container. It makes your content look neat and easy to read.
When you want text to start from the left side of a paragraph or heading.
When you want text to be centered in a button or title.
When you want text to line up on the right side, like dates or prices.
When you want to justify text so it fills the whole line evenly, like in newspapers.
When you want to change alignment for different screen sizes to improve readability.
Syntax
CSS
selector {
  text-align: value;
}
Replace selector with the HTML element or class you want to style.
The value can be left, right, center, or justify.
Examples
Aligns paragraph text to the left side.
CSS
p {
  text-align: left;
}
Centers the heading text.
CSS
h1 {
  text-align: center;
}
Aligns text with class 'price' to the right.
CSS
.price {
  text-align: right;
}
Justifies text in an article so lines fill the width evenly.
CSS
article {
  text-align: justify;
}
Sample Program
This example shows three paragraphs with different text alignments: left, right, and justify. Each has a background color to help you see the alignment clearly.
CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Text Alignment Example</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 2rem;
    }
    header {
      text-align: center;
      margin-bottom: 1rem;
    }
    p.left {
      text-align: left;
      background-color: #e0f7fa;
      padding: 0.5rem;
    }
    p.right {
      text-align: right;
      background-color: #ffe0b2;
      padding: 0.5rem;
    }
    p.justify {
      text-align: justify;
      background-color: #c8e6c9;
      padding: 0.5rem;
    }
  </style>
</head>
<body>
  <header>
    <h1>Text Alignment Demo</h1>
  </header>
  <p class="left">This paragraph is aligned to the left. It looks like normal reading text starting from the left side.</p>
  <p class="right">This paragraph is aligned to the right. It lines up on the right side of the container.</p>
  <p class="justify">This paragraph is justified. The text stretches so both the left and right edges line up evenly, making it look tidy like in books or newspapers.</p>
</body>
</html>
OutputSuccess
Important Notes
Text alignment only affects inline content inside a block container.
Justify alignment can create uneven spaces between words on some lines.
For better accessibility, avoid center-aligning large blocks of text as it can be harder to read.
Summary
Use text-align to control horizontal text placement inside containers.
Common values are left, right, center, and justify.
Text alignment improves the look and readability of your web content.