Home > Web Front-end > JS Tutorial > body text

How to center align text content using JavaScript?

WBOY
Release: 2023-08-24 11:09:06
forward
4308 people have browsed it

如何使用 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>
Copy after login

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>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!