如何使用 JavaScript 將文字內容對齊到中心?


我們可以透過操作元素的 CSS 屬性,使用 JavaScript 將文字內容對齊到中心。這可以透過選擇元素並將 "text-align" 屬性設定為 "center" 來完成。此外,我們還可以使用 "margin" 屬性來調整元素的位置。

方法

有多種方法可以使用 JavaScript 將文字內容居中 −

  • 最常見的方法是在 CSS 樣式表中將text-align屬性設定為"center"。

  • 另一種方法是使用<center>標記。最後,你可以使用 margin 屬性將文字內容居中。

示例

下面我們將看到僅使用 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>

示例

讓我們來看另一個將文字內容對齊到中心位置的示例 −

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

更新時間:2023-02-13

1.3 萬+ 瀏覽量

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.