Skip to content
Related Articles

Related Articles

How to align text content into center using JavaScript ?
  • Last Updated : 23 Dec, 2020

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

Syntax:

object.style.textAlign = "center"

The above syntax set the text alignment into center dynamically.

Example:

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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 onclick="myFunction();">
        Set Alignment
    </button>
  
    <script type="text/javascript">
  
        function myFunction() {
            let txt = document.getElementById("content");
            txt.style.textAlign = "center";
        }
    </script>
</body>
  
</html>

chevron_right


Output:



Before Button Click:

After Button Click:

Supported Browsers: 

  • Google Chrome
  • Internet Explorer
  • Mozilla Firefox
  • Opera
  • Safari

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :