行高的介绍
line-height
作用:设置文本的行高
应用:将文本的行高设置为容器的高度,这样可以将文本在容器中垂直居中。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div{
width: 200px;
height: 100px;
background-color: red;
text-align: center;
font-size: 30px;
line-height: 100px;
}
</style>
</head>
<body>
<div>
四大名著
</div>
</body>
</html>
行高的单位
1.px像素
2. %(百分比), %之前的数据一定是整数。
如果 line-height单位设置为%,那么将来在计算的时候,基数是当前标签中文本的字体(font-size)的大小。如下: 字体大小就位
20px * 150% = 30px
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style >
div{
font-size: 20px;
line-height: 150%;
}
</style>
</head>
<body>
<div>名</div>
</body>
</html>
3. em, em之前的数据一定是小数。
效果跟百分比是一样的。 一行em大小相当于是当前标签中的font-size的大小。
如下: 20px * 1.5 = 30px
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style >
div{
font-size: 20px;
line-height: 1.5em;
}
</style>
</head>
<body>
<div>名</div>
</body>
</html>
4没有单位
如果不涉及到继承,那么带不带单位(em)都是一样的效果。
如果涉及到继承,那么就有比较大的区别:
①如果单位是em,那么将来在继承的时候,我们的浏览器会将行高对应的具体的数值计算出来后再继承。
②如果没有单位,那么将来在继承的时候,我们的浏览器会先将line-height这个属性继承给子元素,再在子元素中计算。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.father{
width:300px;
height: 200px;
background-color: red;
font-size: 20px;
/*如果单位是em,那么将来在继承的时候,我们的浏览器会将行高对应的具体的数值计算出来后再继承。
20px * 1.5 = 30px
line-height: 30px; 然后继承给子元素
*/
/*line-height: 1.5em;*/
/*如果没有单位,那么将来在继承的时候,我们的浏览器会先将line-height这个属性继承给子元素,再在子元素中计算。
子元素的font-size:24px
所以 line-height: 24px*1.5 = 36px;
*/
line-height: 1.5;
}
.son{
background-color: blue;
font-size: 24px;
}
</style>
</head>
<body>
<div class="father">
<div class="son">
四大名著
</div>
</div>
</body>
</html>