Home  >  Article  >  Web Front-end  >  How to center align text content using JavaScript?

How to center align text content using JavaScript?

WBOY
WBOYforward
2023-08-24 11:09:064295browse

如何使用 JavaScript 将文本内容居中对齐?

We can use JavaScript to align text content to the center by manipulating the CSS properties of the element. This can be done by selecting the element and setting the "text-align" property to "center". In addition, we can also use the "margin" attribute to adjust the position of the element.

method

There are multiple ways to center text content using JavaScript -

  • The most common method is to set the text-align property to "center" in the CSS stylesheet.

  • Another way is to use the

    tag. Finally, you can use the margin property to center the text content.

Example

Below we will see code to center 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’s look at another example of center aligning text content -

<!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>

The above is the detailed content of How to center align text content using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete