Javascript Reference - HTML DOM Style textAlign Property








The textAlign property sets or gets the horizontal alignment of text in a block level element.

Browser Support

textAlign Yes Yes Yes Yes Yes

Syntax

Return the textAlign property:

var v = object.style.textAlign 

Set the textAlign property:

object.style.textAlign='left|right|center|justify|initial|inherit'

Property Values

Value Description
left Align the text to the left
right Align the text to the right
center Center the text
justify justify to make line to have same width
inherit inherit the text-align property from the parent element




Technical Details

Default Value: left 
Return Value: A string representing the horizontal alignment of text
CSS Version CSS1

Example

The following code shows how to center-align the text in a <p> element.


<!DOCTYPE html>
<html>
<body>
<p id="myP">This is an example paragraph.</p>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {<!--  ww  w .  java  2  s .c o  m-->
    document.getElementById("myP").style.textAlign = "center";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to get the text alignment of a <p> element.


<!DOCTYPE html>
<html>
<body>
<p id="myP" style="text-align:right;">This is an example paragraph.</p>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from w  w  w.j  a v a2 s . c om-->
    console.log(document.getElementById("myP").style.textAlign);
}
</script>

</body>
</html>

The code above is rendered as follows: