{ hide_text } CSS 文字隱藏方法總結報告

這是我最近整理的一份 CSS 文字隱藏 demo,歸納了幾種方法,本想找出一種最完美的方案收進自己的程式碼片段,誰知最後卻陷入不斷推翻結論的循環。因為需要考量的應用場景與元素實在太多——撇開瀏覽器不談,不同的應用終端、不同的標籤結構,都會有不同的最佳解。因此,與其期望在工作上多「偷懶」,不如平日多鞏固累積基礎知識,如此在需要權衡時才能更得心應手。
由於自己經驗尚淺,demo 部分難免有疏漏,若發現問題,還望大家指正。
1. 毫無保留:display:none
程式碼片段:
(x)HTML
<p class="hide_display">我是打醬油的文本</p>
CSS
/* 暴力隱藏 */
.hide_display{display:none;}
優點:
缺點:
2. 折中選擇:overflow:hidden/position:absolute/visibility:hidden
程式碼片段:
(x)HTML
<span class="hide_overflow">我是一號打醬油的文本</span>
<p class="hide_position">我是二號打醬油的文本</p>
<p class="hide_visibility">我是三號打醬油的文本</p>
優點:
缺點:
3. 體驗損失:text-indent 負值
程式碼片段:
(x)HTML
<p class="hide_tex"><a href="#">我是打醬油的超連結一號</a></p>
<a class="hide_tex_span" href="#"><span>我是打醬油的
超連結二號</span></a>
<!--全英文字符在 IE 下不能被隱藏 -->
<input class="hide_tex_input" type="submit" />
<input class="hide_tex_input" type="submit" />
<button class="hide_tex_input">我是打醬油的文本
btn</button>
CSS
.hide_tex a, .hide_tex_span{
text-indent:-32767px;
display:block; /* text-indent 適用塊狀元素中的行內元素和文本節點 */
/* 演示需要 */
width:200px;
height:20px;
margin-left:300px;
background-color:#ccc;
/* outline:none; 不建議隱藏 outline,鍵盤流選手無法操作 */
}
.hide_tex_input{
text-indent:-32767px;
width:200px;
height:50px;
display:block;
}
優點:
缺點:
4. 牛皮癬:font-size 設零
程式碼片段:
(x)HTML
<p class="hide_fs">我是擦不掉牛皮癬</p>
<button class="hide_fs">我是打醬油的文本btn</button>
<input class="hide_fs" type="submit" />
CSS
.hide_fs{ font-size:0; }
優點:
缺點:
5. 強強聯合:line-height 三倍
程式碼片段:
(x)HTML
<p class="hide_lh"><a href="#">目前為止被正常人類普遍接受的疑似最完美隱藏文字方案,傳說是 tommy 發明的</a></p>
<!-- line-height 在 ff3.6 的 button 無法隱藏文本,需要配合其他方式 -->
<button class="hide_lh_btn">我是打醬油的文本
btn</button>
<!-- line-height 在 ff3.6、opera 的 input 無法隱藏文本,需要配合其他方式 -->
<input class="hide_lh_btn" type="submit" />
<!-- 目前比較完善的方案 -->
<input class="hide_lh_btn_final" type="submit" />
CSS
/* 設定高度,利用行高把文本撐到容器可視範圍外 */
.hide_lh a, .hide_lh_btn{
width:200px;
height:20px;
overflow:hidden;
line-height: 60px;/* 行高最好設 3 倍或以上,chrome 容易露餡 */
display:block;/* 行內元素需要 */
/* 演示需要 */
background-color:#ccc;
margin-left:300px;
}
.hide_lh_btn_final{
width:200px;
height:20px;
overflow:hidden;
line-height:60px;
display:block;
font-size:0px; /* opera 和 ff 支援 */
}
優點:
缺點:
多一丁點:前置背景遮擋
程式碼片段:
(x)HTML
<!-- 在 css 無效和 css 有效但圖片無效時都適用 -->
<a class="hide_bg" href="#"><span
class="front_bg"></span>我是可訪問性的化身</a>
CSS
.hide_bg{
width:200px;
height:20px;
position:relative;
display:block;/* 行內元素需要 */
}
.hide_bg .front_bg{
background:url('bg_text.png') no-repeat; /* 背景內容等於或大於容器大小 */
position:absolute; /* 絕對定位,不影響文本 */
left:0px;
top:0px;
width:200px;/* 與父元素等寬高 */
height:20px;
display:block;
/* cursor:pointer; ie6 和連結需要用 */
}
優點:
缺點:
另闢蹊徑:content:""
程式碼片段:
(x)HTML
<!-- 只有 opera 支援,按定義只能用在 :before 和 :after -->
<a class="hide_ct" href="#">也許我才是最合適的,誰知道呢,內容表現分離。只有 opera 支援</a>
CSS
.hide_ct{ content:""; }
優點:
缺點: