Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to set the horizontal alignment of text with JavaScript?
The textAlign property in JavaScript controls the horizontal alignment of text within an element. You can set it to values like left, right, center, or justify.
Syntax
element.style.textAlign = "alignment_value";
Available Alignment Values
- left - Aligns text to the left (default)
- right - Aligns text to the right
- center - Centers the text
- justify - Stretches text to fill the line width
Example: Setting Right Alignment
<!DOCTYPE html>
<html>
<body>
<p id="myText">This is demo text</p>
<button onclick="display()">Set Right Alignment</button>
<script>
function display() {
document.getElementById("myText").style.textAlign = "right";
}
</script>
</body>
</html>
Example: Multiple Alignment Options
<!DOCTYPE html>
<html>
<body>
<p id="textDemo">This text will change alignment when you click the buttons below.</p>
<button onclick="alignLeft()">Left</button>
<button onclick="alignCenter()">Center</button>
<button onclick="alignRight()">Right</button>
<button onclick="alignJustify()">Justify</button>
<script>
function alignLeft() {
document.getElementById("textDemo").style.textAlign = "left";
}
function alignCenter() {
document.getElementById("textDemo").style.textAlign = "center";
}
function alignRight() {
document.getElementById("textDemo").style.textAlign = "right";
}
function alignJustify() {
document.getElementById("textDemo").style.textAlign = "justify";
}
</script>
</body>
</html>
Getting Current Text Alignment
You can also retrieve the current text alignment value:
<!DOCTYPE html>
<html>
<body>
<p id="sample" style="text-align: center;">Centered text</p>
<button onclick="checkAlignment()">Check Alignment</button>
<p id="result"></p>
<script>
function checkAlignment() {
var element = document.getElementById("sample");
var alignment = element.style.textAlign;
document.getElementById("result").innerHTML = "Current alignment: " + alignment;
}
</script>
</body>
</html>
Key Points
- The
textAlignproperty affects only inline and inline-block elements within the container - Setting alignment through JavaScript overrides CSS styles
- The default value is usually
leftfor left-to-right languages - Use
justifycarefully as it may create uneven spacing in short lines
Conclusion
The textAlign property provides an easy way to control horizontal text alignment dynamically. Use values like left, right, center, or justify to achieve the desired layout.
Advertisements
