How to align text content into center using JavaScript?


We can align text content into the center using JavaScript by manipulating the CSS properties of the element. This can be done by selecting the element and setting the "text-align" property to "center". Additionally, we can also use the "margin" property to adjust the positioning of the element.

Approach

There are multiple ways to center text content using JavaScript −

  • The most common way is to set the text-align property to “center” in the CSS stylesheet.

  • Another way is to use the <center> tag. Finally, you can use the margin property to center text content.

Example

Below we will be seeing the code centering the text using only JavaScript.

<html>
<head>
   <title>JavaScript - Center Text</title>
</head>
   <body>
      <script> 
         const centerText = () => {    
            var centerText = document.createElement('p');
            centerText.innerText = 'Center Text';
            centerText.style.color = 'black';
            centerText.style.textAlign = 'center';
            document.body.appendChild(centerText);
         } 	 
         centerText();
      </script>
   </body>
</html>

Example

Let us see another example to align text content into center −

<!DOCTYPE html>
<html>
<head>
   <title>
      Align Text
   </title>
</head>  
   <body>
      <h1>Demo Heading</h1> 
      <p id="demo">
         This text will be center aligned
      </p> 
      <button onclick="demoFunc();">Align</button> 
      <script>
         function demoFunc() {
            let txt = document.getElementById("demo");
            txt.style.textAlign = "center";
         }
      </script>
   </body>
</html>

Updated on: 13-Feb-2023

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements