元素垂直居中的几种方法

<div class="parent">
  <span>asdlfkjadsl;fjadls;</span>
</div>

方法一

设置父级元素显示方式为表格 ( display: table; ) 这样就可以使用表格的 vertical-align: middle;属性

设置子元素

display: table-cell;

vertical-align: middle;

eg:

.parent {
  width: 100%;
  height: 100px;
  display: table;
}

.child {
  text-align: center;
  display: table-cell;
  vertical-align: middle;
}

优点: 父元素和子元素的高度多高都行

缺点: IE8 不好用

方法二

使用定位,

设置父元素position: relative,

子元素

position: absolute;

top: 50%;

height: 50px;

margin-top: -25px;  margin-top: -高度的一半

.parent {
  background-color: red;
  width: 100%;
  height: 100px;
  position: relative;
}

.child {
  display: inline-block;
  text-align: center;
  height: 50px;
  position: absolute;
  top: 50%;
  margin-top: -25px;

}

缺点: 子元素的高度是固定的

 

方法三

line-height的方式

设置子元素的line-height等于父元素的高度

.parent {

  height: 100px;

}

.child {

  line-height: 100px;

这种方式只能设置单行文本垂直居中

 

方法四

使用vertical-align 加伪元素的方式居中

vertical-align 指的是当前 inline 元素自己,与其它 inline 元素如何对齐

所以给父元素添加一个伪元素, 在对子元素设置vertical-align: middle;就可以实现垂直居中

.parent {
  background-color: var(--fontColor);
  width: 100%;
  height: 100px;
}
.parent::before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

.child {
  display: inline-block;
  text-align: center;
  vertical-align: middle;
}

缺点: 如果需要用伪元素做一些事情的话, 这种方式就不太完美了

 

方法五

transform

类似用定位的方式, 通过transform向上移动高度的一半

.parent {
  background-color: var(--fontColor);
  width: 100%;
  height: 100px;
}

.child {
  display: inline-block;
  text-align: center;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

 

方法六

flexbox, 几乎一切跟布局相关的问题,都能用flexbox解决, 前提是浏览器要支持

justify-content: center;  设置元素在主轴上的对齐方式

align-items: center;    设置元素在交叉轴上的对齐方式

.parent {
  background-color: red;
  width: 100%;
  width: 400px;
  height: 200px;
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
  align-items: center;
}

.child {
  display: inline-block;
  width: 50px;
  height: 50px;
  margin: 8px;
  background-color: green;
  text-align: center;
  line-height: 50px;
}

posted @ 2017-12-26 10:40  五笔  阅读(577)  评论(0编辑  收藏  举报