CSS为什么行高line-height与文字高度height设为一样大,文字就垂直居中了?

html-css06

CSS为什么行高line-height与文字高度height设为一样大,文字就垂直居中了?,第1张

用p元素输出一行文本后:

①line-height(行高)=font-size(字符大小)+word-spasing(上下行间距)

例如:行高设置为100px时,若字符大小为30px,那上下行间距就分别为35px;

重点是:字符上行间距和下行间距的大小是相同的。

②如果你知道height是块级元素的属性,没行内元素什么事,那你对你的问题就不难理解:

试想,一个100px高的div,它的上下padding都设置为35px;中间的content就是30px,此时,它的height(高)=content(内容大小)+padding(上下填充值)。

③结合以①②中的两个等式:当设置line-height等于height时,字符大小就是内容大小,而上下相同的行间距就相当于上下相同的padding。故,div中的内容居中=p元素的字符(撑满容器)居中。

“如果此时我把行高调为60px,那么文字中心点距上或者距下各为30px,那不仍然是垂直居中吗?”

你想想,你说的“垂直居中”是相对什么居中?相对于上一行的文本和下一行的文本垂直居中?确实是这样,但这不是相对包围他们的容器。

你看是这个效果吗

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>无标题文档</title>

<style>

body {background-color: yellow}

/*定义网页背景色为黄色*/

.zairu{

margin:100px auto

width:180px

height:60px

text-align:center

font-size:10px

}

.zairu > div {

background-color: cadetblue

height:60px

width:15px

float: left

display:inline-block /*此元素会作为内联表格来显示(类似 <table>),表格前后没有换行符。*/

-moz-animation: stretchdelay 1.2s infinite ease-in-out/*-webkit-是代表safari、chrome私有属性*,其他的还有-moz-代表火狐 -ms-代表IE*/

animation: stretchdelay 1.2s infinite ease-in-out/*等待1.2S开始动画,动画以低速开始低速结束,animation-delay定义动画何时开始以秒或毫秒计算*/

}

.zairu .zairu2 {

-moz-animation-delay: -1.1s

animation-delay: -1.1s

}

.zairu .zairu3 {

-moz-animation-delay: -1.0s

animation-delay: -1.0s

}

.zairu .zairu4 {

-moz-animation-delay: -0.9s

animation-delay: -0.9s

}

.zairu .zairu5 {

-moz-animation-delay: -0.8s

animation-delay: -0.8s

}

.zairu .zairu6 {

-moz-animation-delay: -0.7s

animation-delay: -0.7s

}

.zairu .zairu7 {

-moz-animation-delay: -0.6s

animation-delay: -0.6s

}

.zairu .zairu8 {

-moz-animation-delay: -0.5s

animation-delay: -0.5s

}

@-moz-keyframes stretchdelay {

0%, 40%, 100% { -moz-transform: scaleY(0.4) }

20% { -moz-transform: scaleY(1.0) }

}/*keyframes代表编辑动画效果 rtransform跟动画效果 scaleY表示2D缩放动画*/

@keyframes stretchdelay {

0%, 40%, 100% {

transform: scaleY(0.4)

-moz-transform: scaleY(0.4)

} 20% {

transform: scaleY(1.0)

-moz-transform: scaleY(1.0)

}

}

</style>

</head>

<body>

<div class="zairu">

<div class="zairu1"><p>L</p></div>

<div class="zairu2"><p>o</p></div>

<div class="zairu3"><p>a</p></div>

<div class="zairu4"><p>d</p></div>

<div class="zairu5"><p>i</p></div>

<div class="zairu6"><p>n</p></div>

<div class="zairu7"><p>g</p></div>

<div class="zairu8">.</div>

</div>

</body>

</html>