1. 程式人生 > >CSS自動換行

CSS自動換行

1、換行

在做專案時有時會出現文字過多,一行不能完全顯示,需要換行顯示的要求,現在瞭解一下下吧^_^。

td元素的nowrap屬性表示禁止單元格中的文字換行,但使用時還要注意,nowrap屬性的行為與td元素的width屬性有關。若未設定td寬度,則nowrap屬性可以起作用,但是若設定td寬度,則nowrap不起作用。

在td元素中可以進行如下的程式碼設定:

<td style="word-break:break-all">

2)<br/>

小換行,與之前的間距大小不變

3)<p></p>

大換行,下上2個段落之間的間距變大。

4)有時設定寬度對連續的英文或數字等無效,需要強制換行,這時就需要用到word-wrap:break-word;或word-wrap:break-all;

當然了,也有文字過多需要顯示前部分o(* ̄︶ ̄*)o

2、顯示部分文字有2種方法,不過都可以用text-overflow

語法:text-overflow : clip | ellipsis

clip :  不顯示省略標記(...),而是簡單的裁切
ellipsis :  當物件內文字溢位時顯示省略標記(...)

1)前部分用文字,後部分用省略號text-overflow : ellipsis

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文件</title>
<style type="text/css"> 
*{ padding:0; margin:0} 
a{ text-decoration:none;color:#6699ff} 
ul,li{ list-style:none; text-align:left} 
 
#divcss5{border:1px #ff8000 solid; padding:10px; width:150px; margin-left:10px; margin-top:10px} 
#divcss5 li{width:150px;height:24px;line-height:24px; font-size:12px;color:#6699ff;overflow:hidden;text-overflow:ellipsis; border-bottom:1px #ff8000 dashed;} 
#divcss5 li a:hover{ color:#333} 
</style> 
</head>

<body>
<ul id="divcss5"> 
<li><a href="#"><nobr>• nobr顯示不完用省略號顯示,測試內容</nobr></a></li> 
<li><a href="#"><nobr>• nobr顯示不完不用省略號顯示,測試內容</nobr></a></li> 
<li><a href="#"><nobr>• nobr能顯示完幾個字</nobr></a></li> 
<li><a href="#">•沒有nobr顯示不完用什麼顯示,測試內容</a></li> 
<li><a href="#">•沒有nobr顯示不完用什麼顯示,測試內容</a></li> 
<li><a href="#"><nobr>• 沒有nobr能顯示完幾個字?</nobr></a></li> 
</ul> 

</body>
</html>

text-overflow

總結:如果想要隱藏溢位的內容,同時又想讓多餘的內容以省略號的形式顯示,這時就需要用到overflow和text-overflow,與此同時,為避免文字自動換行,增加nobr標籤強制內容不換行。即需要用到overlow、text-overflow、nobr。

2)直接擷取text-overflow : clip

3、不換行及不換行的方法

如果我們對li元素設定了寬度,其內容達到設定寬度自動會自動換行,但是有時候因為需要不想讓其換行,希望其在一行顯示。我們可以在對其元素進行CSS設定時,增加white-space:nowrap;

例:有多個超連結,因設定寬度後有的完整的超連結不能在一行展示,我們需要其不換行,這時加上white-space:nowrap;即可實現同一個超連結不被自動分割成兩排顯示。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文件</title>
<style type="text/css"> 
.hDiv{ width:180px; line-height:20px;}
.hDiv a{ margin: 0 5px; white-space:nowrap;}
</style> 
</head>

<body>
<div class="hDiv">
    <a href="#">我是超連結1</a><a href="#">我是超連結2</a>
    <a href="#">我是超連結3</a><a href="#">我是超連結4</a>
    <a href="#">我是超連結5</a><a href="#">我是超連結6</a>
    <a href="#">我是超連結7</a><a href="#">我是超連結8</a>
</div>
</body>
</html>