行高 line-height 知识小结

838 阅读1分钟

line-height设置文字行高,首先来看下它的几个属性以及作用:

  • line-height:normal,这里 normal

  • 根据浏览器决定,不同浏览器表现不同,且与元素字体关联,主要是干和父元素继承的关系。

  • line-height:1.5em/15px/1.5rem/20px; 具体长度值

  • line-height:10% 百分比作为行高值

  • line-height:inherit 继承父元素

  • input{ line-height: inherit} input等元素默认行高是normal,使用inherit可以让文本框样式可控性更强。

这两种行高计算方式的区别:

line-height:1.5;
line-height:1.5rem/150%;

一、第一个,是利用字体自身的 font-size*1.5,假设字体自身的 font-size 是 30px,那么行高就是 30 * 1.5。

二、第二个,是继承父元素的 font-size*150%,假设父元素的 font-size 是 20px,自身的 font-size 是 30px,那么行高就是 20 * 150%。

一般使用经验,匹配 20 像素的使用经验----方便心算。

假设 body 的 font-size 是 14px
line-height = 20px / 14px = 1.42857
body{ font:14px/1.4286 font-family:'microsoft yahei}

应用:

图片水平垂直居中

.box { line-height:300px; text-align: center }
.box > img { vertical-align:middle }

兼容性: ie8+

多行文本水平垂直居中

.box { line-height:250px; text-align:center }
.box > .text { display:inline-block; line-height: normal; text-align: left; vertical-align:middle }

兼容性: ie8+

如果一个容器的 css 样式如下,{height:36px;line-height:36px},height:36px 其实是多余的,可以直接干掉。 因为,内联元素的高度其实有 line-height 决定的。