Quick Reach
Text alignment in CSS
Setting the alignment of text is quite simple in CSS. The CSS text-align property is used to set the alignment of the text horizontally. As per requirement, you can use the left, right, and center values in the text-align property.
The default alignment value of the align property is left if the direction property value is ltr (which is the default). If direction property value is set to rtl then default alignment will be right.
Align right example
To align text vertically, see its respective chapter. This chapter will only explain CSS horizontal align property/values.
See the following examples of using the text-align CSS property for horizontal alignment using different values in different elements.
Align center using CSS text align in div element
The following example shows how to use the text-align property. We will set a div element aligned to center. Also, we will use align center value in <h1> and <h2> tags. You may have a look by clicking the image or link below:
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
<html>
<head>
<style>
/*Using CSS text*/
h1
{
background-color: #F0F0F0;
color: #355681;
text-align: center;
}
h2
{
background-color: #355681;
color: white;
text-align: center;
}
div
{
background-color: #F0F0F0;
color: rgb(000,125,255);
text-align: center;
}
</style>
</head>
<body>
<h1>heading 1 center align</h1>
<h2>Heading 2 center align</h2>
<div>Div center align</div>
</body>
</html>
|
As you can see in the demo, the div alignment is the center (3rd element from top). Also, the headings are also centralized by using the center value in the text-align property.
An align right example
This example sets the text alignment to the right of a div and headings (h1,h2) by using text align property.
Also, we used the direction property to rtl for heading (h1), so if you do not set the text-align as right for <h1>, the default is still the right.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
<html>
<head>
<style>
/*Using CSS text*/
h1
{
background-color: #F0F0F0;
color: #355681;
direction: rtl;
}
h2
{
background-color: #355681;
color: white;
text-align: right;
}
div
{
background-color: #F0F0F0;
color: rgb(000,125,255);
text-align: right;
}
</style>
</head>
<body>
<h1>heading 1 right align by default</h1>
<h2>Heading 2 right align</h2>
<div>Div right align</div>
</body>
</html>
|
Further: CSS line-height | CSS vertical-align
Leave A Comment?