How to Align Text in Javascript?

We will learn in this blog post how a paragraph text can be aligned with the click of a button. We are going to use the Style textAlign property here.

The text-align CSS property sets the horizontal alignment of the content inside a block-level element. This means it works like vertical-align but in the horizontal direction.

CSS Demo: text-align “justify”

<!DOCTYPE html>
<html>
<body>

<p id="demo">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

<button type="button" onclick="myFunction()">Align text</button>

<script>
function myFunction() {
  document.getElementById("demo").style.textAlign = "justify";
}
</script>

</body>
</html>

Result

CSS Demo: text-align “Center”

<!DOCTYPE html>
<html>
<body>

<p id="demo">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

<button type="button" onclick="myFunction()">Align text</button>

<script>
function myFunction() {
  document.getElementById("demo").style.textAlign = "center";
}
</script>

</body>
</html>

Result

text align center
text align center

Another example of Text Align in javascript

text-align: start;

text-align: end;

text-align: center;

text-align: justify;

text-align: right;

text-align: left;

text-align: initial;

text-align: inherit;

I hope this blog post will be helpful for you.