nfssuzukaze / Blog

0 stars 0 forks source link

深入 CSS 的 line-height 与 vertical-align 属性 #1

Open nfssuzukaze opened 4 years ago

nfssuzukaze commented 4 years ago

1. 前置知识

1.1 组成一个完整的盒模型需要:

2. vertical-align

2.1 vertical-align 的取值(主要)

3. line-height

3.1 line-height 的取值

在一个元素中, 我们可以将每行看作一个 line box 在一个 line box 中, 存在至少一个 inline box , 该 inline box 的高度为其对应的 line-height 而一个 line box 的高度为 max(任意一个 inline box 的顶端到任意一个 inline box 底部的距离)

image

正常情况下, line-height 都比 content area height 要大, 而其多出来的长度, 一半会加到 content area 的顶部, 另一半会加到 content area 的底部

4. 由 line-height 与 vertical-align 导致的问题

1. 当仅两个 spandiv 中, 且 spanfont-family 相同, line-height 相同时, 更改 font-size 会导致 div 元素的高度改变

1.1 原代码

  <div>
    <span class="first">xxx</span>
    <span class="second">xxx</span>
  </div>
div {
  margin: 40px;
  width: 400px;
  background-color: red;
}

div > .first {
  font-size: 50px;
  width: 100px;
  line-height: 100px;
  background-color: yellow;
}

div > .second {
  font-size: 50px;
  width: 100px;
  line-height: 100px;
  background-color: lightgreen;
}

1.2 将第二个 span 中的 font-size 变小

div > .seconde {
  font-size: 30px;
  width: 100px;
  line-height: 100px;
  background-color: lightgreen;
}

02 01

原因:

  1. 由于 vertical-align 的属性默认是 baseline , 所以在同一行中, 两个 spanx 字母的 baseline 会对齐,
  2. 但由于第二组的 xfont-size 相对较小, 那么自然其 content area 的高度会缩小,
  3. 又由于 baselinecontent area 中所处的位置偏下, 所以baseline 之下的 content area 高度的缩小幅度小于总缩小幅度的 1/2baseline 之上的 content area 高度的缩小幅度大于总缩小幅度的 1/2,
  4. line-height 多出来的值又会各分 1/2 分别添加到 content area 的顶部与底部
  5. 所以就导致了这个 inline box 的顶部与底部都降低了
  6. 所以就导致了这个 line box 的顶部不变(较大字体 inline box 的顶部) , 而底部降低(较小字体 inline box 的底部)
  7. line box 高度增高

03

解决方法: 将两个子元素的 inline-height 设置为相同的数值

2. 放一张图片或一个 inline-block 元素进没有指定高度的元素中, 会导致子元素底部还会有一点空隙

<div><span></span></div>
body {
  background-color: yellow;
}

div {
  display: block;
  margin: 20px;
  width: 500px;
  background-color: grey;
}

span {
  display: inline-block;
  height: 200px;
  width: 200px;
  background-color: #fff;
}

05

解决方法:

  1. 将对应的子元素的 display 改为 block
  2. 将对应的子元素的 vertical-align 设置为 middletopbottom
  3. 将对应的子元素的 line-height 设置为 0
  4. 将对应的父元素的 font-size 设置为 0