CSS篇-垂直居中

css 垂直居中的几种手段

  1. height + line-height
  2. vertical-align
  3. padding
  4. flex + align-items
  5. 绝对定位 + margin: auto
  6. 绝对定位 + margin:-height/2
  7. 绝对定位 + transform
  8. flex + flex-direction
  9. grid

height + line-height

使用:父元素 为 block 元素,子元素为 display: inline-block 元素。

.parent{
	display: block;
	height: 120px;
	line-height: 120px;
	text-align:center;
}
.son {
	display: inline-block;
}
复制代码

vertical-align: middle

使用: 利用 vertical-align: middle 实现

.parent {
	display: table;
	width: 120px;
	height: 120px;
  text-align:center;
}
.son {
	display:table-cell;
	vertical-align: middle;
}
复制代码

padding

使用:当确定子 元素 宽度和高度的时候使用

.parent {
  display: block;
  width:120px;
  padding: 80px 0;
  text-align:center;
}
.son {
 height: 80px;
 line-height: 80px;
 width: 120px;
}
复制代码

flex+align-items

使用: 兼容性

.parent {
  display:flex;
  width: 120px;
  height: 120px;
  text-algin:center;
  align-items:center;
}
.son {
	width:60px;
}

复制代码

绝对定位 + margin: auto

使用:当确定子 元素 宽度和高度的时候使用

.parent {
  display: block;
  width:120px;
  height:120px;
  position:relative;
  text-align:center;
}
.son {
  position:absolute;
  margin: auto;
  top: 0;
  bottom: 0;
  width: 120px;
  height: 50px;
  line-height: 50px;
}
复制代码

绝对定位 + margin:-height/2

使用:当确定子 元素 宽度和高度的时候使用

.parent {
  display: block;
  width:120px;
  height:120px;
  position:relative;
  text-align:center;
}
.son {
  position:absolute;
  left: 50%;
  top: 50%;
  width: 50px;
  height: 50px;
  line-height: 50px;
  margin-left: -25px;
  margin-top: -25px;
}
复制代码

绝对定位 + transform

使用:兼容性

.parent {
  position:relative;
  width: 120px;
  height: 120px;
  text-align:center;
}
.son {
  position:absolute;
  top: 50%;
  width: 100%;
  transform: translateY(-50%);
}
复制代码

flex+flex-direction

使用:兼容性

.parent {
	display:flex;
	width:120px;
	height: 120px;
  flex-direction: column;
   justify-content: center;

}
.son {
  height: 80px;
  width: 180px;
  line-height: 80px;
}

复制代码

Grid

使用: 兼容性

.parent {
  width: 200px;
  height: 200px;
  display: grid;
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享