最近整理了一份 CSS 文字隱藏的 Demo,總結了幾種常見方法,原本想篩選出一個「完美方案」加入代碼片段庫,結果卻陷入不斷推翻結論的循環。原因在於應用場景與元素類型太過多樣:不考慮瀏覽器差異,不同終端、不同標籤結構往往需要不同的最優策略。與其在工作中偷懶尋找萬能銀彈,不如平時多夯實基礎,臨場才能遊刃有餘。
因經驗有限,Demo 難免疏漏,歡迎指正補充。
display: none<p class="hide_display">我是打醬油的文本</p>
.hide_display { display: none; }

overflow:hidden / position:absolute / visibility:hidden<span class="hide_overflow">文本1</span>
<p class="hide_position">文本2</p>
<p class="hide_visibility">文本3</p>
.hide_overflow { height:0; overflow:hidden; display:block; float:left; }
.hide_position { position:absolute; left:-32767px; }
.hide_visibility { visibility:hidden; position:absolute; margin-left:-32767px; }

visibilitytext-indent 負值<p class="hide_tex"><a href="#">超鏈接一號</a></p>
<a class="hide_tex_span" href="#"><span>超鏈接二號</span></a>
<input class="hide_tex_input" type="submit" />
<button class="hide_tex_input">文本 btn</button>
.hide_tex a, .hide_tex_span { text-indent:-32767px; display:block; width:200px; height:20px; }
.hide_tex_input { text-indent:-32767px; width:200px; height:50px; display:block; }

text-indent 易產生 Bug;全英文字符在 IE 下無法隱藏font-size: 0<p class="hide_fs">擦不掉的牛皮癬</p>
<button class="hide_fs">文本 btn</button>
<input class="hide_fs" type="submit" />
.hide_fs { font-size:0; }

line-height 三倍法<p class="hide_lh"><a href="#">疑似最完美方案</a></p>
<button class="hide_lh_btn">文本 btn</button>
<input class="hide_lh_btn" type="submit" />
<input class="hide_lh_btn_final" type="submit" />
.hide_lh a, .hide_lh_btn { width:200px; height:20px; overflow:hidden; line-height:60px; display:block; }
.hide_lh_btn_final { width:200px; height:20px; overflow:hidden; line-height:60px; display:block; font-size:0; }

<a class="hide_bg" href="#"><span class="front_bg"></span>可訪問性的化身</a>
.hide_bg { /* 代碼未完整 */ }
此法在 CSS 無效或圖片失效時均能工作,屬於漸進增強策略。
沒有放之四海而皆準的「完美隱藏術」。實務中需根據具體場景(是否需螢幕閱讀器讀取、是否為超鏈接、是否為表單元素、是否需 SEO 友好等)權衡選擇。建議建立自己的方案庫,並持續驗證與更新。