Sunday, September 7, 2025
HomeLanguagesJavascriptHow to align text content into center using JavaScript ?

How to align text content into center using JavaScript ?

In this article, we will align the text content into the center by using JavaScript. We use HTML DOM style textAlign property to set the alignment of text.

The DOM style textAlign property is pretty much similar to the text-align property in the CSS, and the Dom textAlign property returns the horizontal alignment of the text in a block-level element in an HTML page and allows for changes to that alignment.

Syntax:

object.style.textAlign = "center"

The above syntax set the text alignment into the center dynamically.

Example: This example aligns the text content into the center using javascript.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>
        How to align text content into
        center using JavaScript ?
    </title>
</head>
 
<body>
    <h1 style="color: green;">
        neveropen
    </h1>
 
    <h3>
        How to align text content into
        center using JavaScript ?
    </h3>
 
    <p id="content">
        neveropen: A computer
        science portal for neveropen
    </p>
 
    <button onclick="myFunction();">
        Set Alignment
    </button>
 
    <script type="text/javascript">
        function myFunction() {
            let txt = document.getElementById("content");
            txt.style.textAlign = "center";
        }
    </script>
</body>
</html>


Output:

 

RELATED ARTICLES

Most Popular

Dominic
32271 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6641 POSTS0 COMMENTS
Nicole Veronica
11807 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6754 POSTS0 COMMENTS
Ted Musemwa
7030 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS