css中的各种居中

垂直居中

垂直居中一个块级元素

知道该块级元素的高

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  height: 100px;
  margin-top: -50px; 
}

不知道该块级元素的宽高

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

使用 flexbox

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

垂直居中一个行内元素

单行文本

一般使 height 和 line-height 相同即可

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

若父元素高度未指定可设置上下 padding 相等

.text-center{
    width: 100px;
    background-color: pink;
    padding-top: 40px;
    padding-bottom: 40px;
}

多行文本

方案1

div {
   display: table;
}
div p {
   display:table-cell;
   vertical-align: middle;
}

方案2

<div class="flex-center">
  <p>I'm vertically centered multiple lines of text in a flexbox container.</p>
</div>

body {
  background: #f06d06;
  font-size: 80%;
}

div {
  background: white;
  width: 240px;
  margin: 20px;
}

.flex-center {
  background: black;
  color: white;
  border: 10px solid white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 200px;
  resize: vertical;
  overflow: auto;
}
.flex-center p {
  margin: 0;
  padding: 60px;
}

方案3 - 诡异的方法

<div class="ghost-center">
  <p>I'm vertically centered multiple lines of text in a container. Centered with a ghost pseudo element</p>
</div>

body {
  background: #f06d06;
  font-size: 80%;
}

div {
  background: white;
  width: 240px;
  height: 200px;
  margin: 20px;
  color: white;
  resize: vertical;
  overflow: auto;
  padding: 20px;
}

.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;
  width: 190px;
  margin: 0;
  padding: 20px;
  background: black;
}

水平居中

水平居中一个块级元素

.center-me {
  margin: 0 auto;
}

水平居中一个行内元素

.center-children {
  text-align: center;
}

垂直水平居中

固定宽高

.parent {
  position: relative;
}

.child {
  width: 300px;
  height: 100px;
  padding: 20px;

  position: absolute;
  top: 50%;
  left: 50%;

  margin: -70px 0 0 -170px;
}

不知道宽高

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

使用 flexbox

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

css居中各种方法