Home >Web Front-end >JS Tutorial >How to center align text content using 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.
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
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>
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!