html css 垂直居中(二)
在html css 垂直居中(一) 中介绍了《css 揭秘》 中的垂直居中的方法,很显然在很多情况下是可以解决的,也是最好的解决方案,但是在某些特定的情况下还是要根据具体的情况而选择合适的方法,这篇同样介绍了一些垂直居中的方法,分享于大家兵记录。
line-height
line-heigth 属性是针对:父元素高度确定的单行文本(内联元素)1
2
3
4
5
6
7
8
9
10//html
<div class="parent">
	<div class="child"></div>
</div>
//css
<style>
	.child{
		line-height: 100px;
	}
</style>
这种方式虽然简单但缺点很明显,仅限于单行文本,而且文字超出容器不会自适应。但它只能用于 inline 元素
table-cell
父元素高度确定的多行文本(内联元素)1
2
3
4
5
6
7
8
9
10
11.parent{
  border: 1px solid blue;
  height: 200px; /* maybe any height */
  display: table;
}
.child{
  display: table-cell;
  border: 1px solid green;
  vertical-align: middle;
}
设置 display: table-cell; 也可以实现垂直居中,但是也存在很多不足,文字超出容器不会自适应。但它只能用于 inline 元素
伪元素
为一个元素添加为元素,相当于为当前元素添加了子元素,因此为了生成一个 100% 高度的伪元素,我们需要对父元素添加伪元素1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20.parent{
  border: 1px solid blue;
  height: 200px;
}
.parent::before {
  content: '';
  display: inline-block;
  vertical-align: middle;
  height: 100%;
  font-size: 0;
}
.child{
  display: inline-block;
  vertical-align: middle;
  border: 1px solid green;
  width: 100%;
  box-sizing: border-box;
}
使用伪元素的缺点在于,当我们要使用父元素的伪元素做一些操作时,同时又让其垂直居中,那我们就无能为力了。
transform
使用 transform 可以用 translateY(-50%) 来达到 - height/2 的目的,而不需要知道居中元素的高度。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23//html
<div class="container">
  <div class="vertical">
    <p>
      transform 实现垂直居中
    </p>
  </div>
</div>
//css
<style>
	.container {
	  border: 1px solid blue;
	  height: 200px; /* maybe any height */
	}
	.vertical {
	  position: relative;
	  top: 50%;
	  transform: translateY(-50%);
	  border: 1px solid green;
	}
</style>
flexbox
最终我们还是要用flexbox,在前面一篇文章中也提到了flexbox,在此提到加深记忆。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21//html
<div class="container">
    <p id="p1">flexbox 垂直居中111 </p>
    <p id="p2">flexbox 垂直居中222</p>
</div>
//css
<style>
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 300px;
  border: 1px solid blue;
}
p {
  border: 1px solid green;
}
</style>
需要注意的是 CSS3 的支持问题。例如 IE 需要 IE11 才能支持。
