css 垂直居中方法总结

1.为内联元素

1.1  只有一行的情况下

可以用padding值。

.link {
  padding-top: 30px;
  padding-bottom: 30px;
}

  

或者使用line-height,line-height等于height值  

.center-text-trick {
  height: 100px;
  line-height: 100px;
  white-space: nowrap;
}

1.2  内容有多行

首先也可以使用padding;也可尝试与display:table-cell相结合设置vertical-align:middle;

或者用flexbox, A single flex-child can be made to center in a flex-parent pretty easily.前提是父级的高度固定

.flex-center-vertically {
  display: flex;
  justify-content: center;
  flex-direction: column;
  height: 400px;
}

 

或者使用"ghost element" , in which a full-height pseudo element is placed inside the container and the text is vertically aligned with that.

.ghost-center {
  position: relative;
}
.ghost-center::before {
  content: " ";
  display: inline-block;
  height: 100%;
  width: 1%;
  vertical-align: middle;
}
.ghost-center p {
  display: inline-block;
  vertical-align: middle;
}

2.块元素

2.1 高度已知

 一般来说是不知道高度的,但当你确实知道时

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  height: 100px;
  margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */
}

2.2 高度未知

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

2.3 使用flexbox将会容易很多

.parent {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

 

参考:  https://css-tricks.com/centering-css-complete-guide/

posted @ 2017-02-27 17:01  慕容文刀  阅读(146)  评论(0编辑  收藏  举报