當一段文字超出容器寬度時,我們常希望它自動截斷並顯示省略號(…)。下面這份範例示範了如何用純 CSS 實現這個常見效果。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS省略號代碼</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
body{
padding:10px;
font-family:Arial;
}
#ididid{
position:relative;
width:150px;
height:20px;
line-height:20px;
text-overflow:ellipsis;
white-space:normal;
*white-space:nowrap;
overflow:hidden;
border:1px solid #999;
}
#ididid span{
position:absolute;
top:0;
right:0;
display:block;
float:left;
}
#ididid span:after{content:"...";}
</style>
</head>
<body>
<div id="ididid">歡迎來到程序員部落<span></span></div>
</body>
</html>
關鍵屬性有三個:text-overflow:ellipsis 負責在截斷處顯示省略號;white-space:nowrap 讓文字不換行(這裡用兼容寫法兼顧 IE);overflow:hidden 則隱藏溢出的部分。三者搭配,就能實現單行文字超出寬度自動省略的效果。
此外,範例還在容器內放了一個靠右定位的 span,透過 :after 補上「...」,作為部分瀏覽器下的補充方案。