Home »
CSS
How to set Text alignment in HTML using CSS?
In this tutorial, we will learn, how to set the text alignment using CSS?
By Apurva Mathur Last updated : July 28, 2023
Aligning a text on your page properly is one of the most important factors while designing your web page. HTML provides us a property that helps us to suitably place a text on its desired position, we can also say that this property helps us to neatly format the text on the page.
Setting alignment to text using CSS
To set text alignment, you can simply use the CSS text-align property with the appropriate value (left, center, right, or justify). The text-align property with the 'left' value sets the text to the left alignment, the 'center' value sets the text to the center alignment, and the 'right' value sets the text to the right alignment, and so on.
Syntax
Below are the syntaxes to set the text alignment to left, center, right, or justify using CSS:
p {
text-align-last: right;
}
p {
text-align-last: center;
}
p {
text-align-last: right;
}
p {
text-align-last: justify;
}
Example to set text alignment using CSS classes
In this example, we are creating 3 classes .center, .right, and .left to align the text of the given DIVs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style type="text/css">
.center
{
text-align: center;
}
.right
{
text-align: right;
}
.left
{
text-align: left;
}
</style>
<body>
<div class="center">
<h2>Text align center</h2>
</div>
<div class="right">
<h2>Text align right</h2>
</div>
<div class="left">
<h2>Text align left</h2>
</div>
</body>
</html>
The output of the above example is:
Example to set text alignment using CSS style attribute
To set text alignment in HTML, use the style attribute. The style attribute specifies an inline style for an element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div style="text-align:center;">
<h2>Text align center</h2>
</div>
<div style="text-align:right;">
<h2>Text align right</h2>
</div>
<div style="text-align:left;">
<h2>Text align left</h2>
</div>
</body>
</html>
CSS Examples »