元素水平垂直居中对齐

306 阅读1分钟

思维导图:zhimap.com/m/SCqqCKMp

1 水平居中

1.1 inline/inline-block

当元素的 display 属性为 inline 或者 inline-block,只要设置 text-align:center; 即可实现水平居中。

.inner {
    display: inline/inline-block;
    text-align: center;
}

1.2 block

当元素的 display 属性为 block,需要设置 margin-left: auto;margin-right: auto; 来实现水平居中。

.inner {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

2 垂直居中

方法一:Position Absolute

.outter {
  position: relative;
}

.inner {
  position: absolute;
  /* 水平垂直居中 */
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

方法二:Flexbox

.outter {
  /* 子元素垂直居中 */
  display: flex;
  justify-content: center;
  align-items: center;
}

方法三:Display Table

.outter {
  border: 5px solid red;
  height: 100px;
  width: 100px;
  display: table;
}
.td {
  border: 5px solid black;
  display: table-cell;
  /* 子元素垂直居中 */
  vertical-align: middle;
}
.inner {
  border: 1px solid blue;
  height: 50px;
  width: 50px;
  /* 子元素水平居中 */
  margin-right: auto;
  margin-left: auto;
}