Text centering in HTML is one of the most common tasks in web design. Whether you need to align a heading, a paragraph, or a block of content, there are different ways to achieve it.
In this article, we’ll explore how to center text in HTML using the CSS properties text-align: center;
and text-align: justify;
, explaining their differences and applications.
To center text in HTML, you use the text-align
property in CSS. Below is an example of how to center text in HTML within a container:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Center Text in HTML</title> <style> .centered { text-align: center; } </style> </head> <body> <p class="centered">This text is centered in HTML.</p> </body> </html>
In this example, the .centered
class ensures that the text is aligned to the center.
The simplest way to center text in HTML is by applying text-align: center;
. This property works well for block-level elements such as <p>
, <div>
, and <h1>
.
p { text-align: center; }
This code will center all paragraph text horizontally on the page.
However, this method does not work for inline elements like <span>
. To center these, you need to use display: block;
or flexbox
.
If instead of centering the text you want to justify it, you can use text-align: justify;
. This evenly distributes the content across the width of the container.
div { text-align: justify; }
This is useful for long texts, improving readability and visual design.
text-align: center;
: Recommended for headings, quotes, and short texts.text-align: justify;
: Ideal for articles, news, or long paragraphs in professional layouts.
Both methods allow you to align text in HTML depending on the context.
Knowing how to center text in HTML is essential for improving a website’s appearance. While text-align: center;
is ideal for central alignments, text-align: justify;
provides a structured and professional format. Depending on your needs, you can choose the right method for each case.