The textAlign property sets or returns the horizontal alignment of text in a block level element.
Syntax and Usage
Return the textAlign property: object.style.textAlign Set the textAlign property: object.style.textAlign = "left|right|center|justify|initial|inherit"
Property Values
| Value | Description |
|---|---|
| left | Aligns the text to the left. This is default |
| right | Aligns the text to the right |
| center | Centers the text |
| justify | The text is justified |
| initial | Sets this property to its default value. |
| inherit | Inherits this property from its parent element. |
<button class="btn btn-success" onclick="ta_center()">Align to center</button>
<h2 id="demo1">This is an example paragraph.</h2>
<script>
function ta_center() {
document.getElementById("demo1").style.textAlign = "center";
}
</script>
<h2 id="demo2" style="text-align:right;">This is an example paragraph.</h2>
<button class="btn btn-success" type="button" onclick="get_alert()">Return text alignment of p</button>
<script>
function get_alert() {
alert(document.getElementById("demo2").style.textAlign);
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Use CSS Style TextAlign Properties In JavaScript</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
h1{
color: red;
}
</style>
<body>
<div class="container">
<div class="text-center">
<h1>Use CSS Style TextAlign Properties In JavaScript</h1>
</div>
<br>
<div class="well">
<button class="btn btn-success" onclick="ta_center()">Align to center</button>
<h2 id="demo1">This is an example paragraph.</h2>
<h2 id="demo2" style="text-align:right;">This is an example paragraph.</h2>
<button class="btn btn-success" type="button" onclick="get_alert()">Return text alignment of p</button>
</div>
</body>
</html>
<script>
function ta_center() {
document.getElementById("demo1").style.textAlign = "center";
}
function get_alert() {
alert(document.getElementById("demo2").style.textAlign);
}
</script>