Open In App

How to align text content into center using JavaScript ?

Last Updated : 28 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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"

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;">
        GeeksforGeeks
    </h1>
 
    <h3>
        How to align text content into
        center using JavaScript ?
    </h3>
 
    <p id="content">
        GeeksforGeeks: A computer
        science portal for geeks
    </p>
 
    <button style="cursor: pointer;"
            id="button" onclick="myFunction();">
        Set Alignment
    </button>
 
    <script type="text/javascript">
        function myFunction() {
            let buttontext = document.getElementById("button");
            buttontext.innerHTML = "Text center Alinged"
            let txt = document.getElementById("content");
            txt.style.textAlign = "center";
        }
    </script>
</body>
</html>


Output:

text-align



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads