css沒有提供一個直接設置行間距的方式,所以只能通過設置行高來間接的設置行間距,行高越大行間距就越大,用 line-height 來設置行高。
.p1 {
/* 設置行高 */
line-height: 40px;
}
行高類似於上學時使用的單線本,單線本是一行一行的線,線與線之間的距離就是行高,網頁中的文字實際上是寫在一個看不見的線中的,而文字會默認在行高中垂直居中顯示。
行間距 = 行高 - 字體大小
line-height 可以設置的值的類型:
- 直接接收一個大小,如:line-height: 20px;
- 可以指定一個百分數,如:line-height: 100%;
- 可以直接指定一個數字,不帶單位,如:line-height: 1.5;
/* 行間距 = 40px(行高) - 20px(字體大小) 為 20px */
.p1 {
/* 字體大小 */
font-size: 20px;
/* 行高為 40px */
line-height: 40px;
}
/* 行間距 = (200% * 20px(字體大小))(行高) - 20px(字體大小) 為 20px */
.p1 {
/* 字體大小 */
font-size: 20px;
/* 行高 = 200% * 20px(字體大小) 為 40px */
line-height: 200%;
}
/* 行間距 = (2 * 20px(字體大小))(行高) - 20px(字體大小) 為 20px */
.p1 {
/* 字體大小 */
font-size: 20px;
/* 行高 = 2 * 20px(字體大小) 為 40px */
line-height: 2;
}
對於單行文本,可以將行高設置為和父元素的高度一致,這樣可以將單行文本在父元素中垂直居中,注意,一定是單行文本
.box1 {
width: 200px;
height: 200px;
background-color: aquamarine;
/* line-height 等於 height,單行文本就會在父元素內垂直居中 */
line-height: 200px;
}
<div class="box1">
<a href="#">蜀道之難,難於上青天!</a>
</div>
在 font 屬性中也可以指定行高,在字體大小的后面添加 "/行高",該值是可選的,如果不指定則會使用默認值。
/* 格式 */
.p1 {
/* 在字體后面加 “/50px”,表示行高 */
font: bold italic normal 30px/50px 微軟雅黑, 宋體, Serif;
}
/* 錯誤的寫法 */
.p1 {
/* 在此設置行高,不會起作用,相反font的"/50px"會起作用 */
line-height: 100px;
/* 在字體后面加 “/50px”,表示行高 */
font: bold italic normal 30px/50px 微軟雅黑, 宋體, Serif;
}
/* 錯誤的寫法 */
.p1 {
/* 在此設置行高也不會起作用 */
line-height: 100px;
/* 在字體后面未設置行高,會使用默認值而不是用上面設置的行高 */
font: bold italic normal 30px 微軟雅黑, 宋體, Serif;
}
/* 正確的寫法 */
.p1 {
/* 在字體后面未設置行高 */
font: bold italic normal 30px 微軟雅黑, 宋體, Serif;
/* 行高 */
line-height: 100px;
}
/* 正確的寫法 */
.p1 {
/* 在字體后面設置行高 "/100px" */
font: bold italic normal 30px/100px 微軟雅黑, 宋體, Serif;
}