ASP.NET WebForms 中 Label 控件實現文字水平與垂直居中(使用 IDE 屬性編輯)
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/1277
在 ASP.NET WebForms 項目中,Label
控件最終會輸出成一個 <span>
元素。這種元素屬於 行內元素 (inline),如果直接在屬性裡調整,文字往往無法達到想要的水平、垂直居中效果。
最常見的需求是:給 Label 外面包一個 div,加上邊框,並讓文字水平 + 垂直居中顯示。
本文記錄一個最簡單實用的方案:利用 Visual Studio 的 Modify Style 編輯器,完全不手寫 CSS class,就能達到效果。
一、準備工作
-
打開你的 WebForms 頁面(例如
WebForm_Menu_1000.aspx
)。 -
在
<form runat="server">
中插入一個外層<div>
,並放一個Label
控件:
<div>
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</div>
二、用 Visual Studio 修改樣式
-
選中外層 div
在設計器或者 Source 視圖中,將光標定位到外層<div>
。 -
右鍵 → Modify Style…
打開「Modify Style」對話框。 -
設置邊框
-
切換到左邊的 Border 分類
-
設定:
-
Style →
solid
-
Width →
1px
-
Color →
#000000
這樣 div 會有黑色邊框。
-
-
-
設置寬度和高度
-
切換到 Position 分類
-
Width →
200px
-
Height →
50px
-
-
設置文字水平居中
-
切換到 Block 分類
-
text-align
→center
-
-
設置文字垂直居中
-
依然在 Block 分類
-
line-height
→50px
(和高度一致)
-
三、最終效果代碼
Visual Studio 會自動生成以下 style:
<div style="border: 1px solid #000000;
text-align: center;
display: block;
width: 200px;
height: 50px;
line-height: 50px;">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
四、效果演示
-
外層 div 顯示為 200×50px 的矩形框
-
框線為黑色實線邊框
-
Label 的文字「Label」在該框內 水平居中、垂直居中
五、方法原理
這裡的關鍵在於 line-height
:
-
height:50px;
→ 固定 div 的高度 -
line-height:50px;
→ 把該行文字的「行框」高度設為和 div 一樣 -
這樣文字自然就上下置中顯示
⚠️ 注意:這個方法只適合 單行文字。如果文字可能換行,建議改用 display:table-cell; vertical-align:middle;
或 CSS3 Flexbox。
六、總結
-
使用 Visual Studio 的 Modify Style 編輯器,不需要自己寫 CSS 文件,也能快速實現效果。
-
操作步驟:Border → 設邊框 → Position → 設寬高 → Block → 設 text-align 和 line-height。
-
適合需要快速調整單行 Label 顯示的場景。
✍️ 個人心得:這個方法非常適合入門和小範圍調整。雖然在專案中推薦用 CSS class 統一管理樣式,但如果只是臨時實驗或局部樣式,這個方式又快又直觀。
This article was last edited at