CSS居中彻底指南

原载于CSS-Trick,本文着重提取文中的方法,不彻底翻译。若有须要,直接原文查看。css

人们常常抱怨在CSS中居中元素的问题,其实这个问题其实并不复杂,只是由于方法众多,须要根据状况从众多方法中选取一个出来。接下来,咱们作一个‘决定树’来帮咱们把问题变的简单一点。首先你须要居中:ide

  • 水平flex

    • 须要居中 inline 或者 inline-* 元素(如文字或者连接)?ui

    • 须要居中 block 类的元素?flexbox

    • 须要居中多个 block 元素?spa

  • 垂直翻译

    • 须要居中 inline 或者 inline-* 元素(如文字或者连接)?code

    • 须要居中 block 类的元素?orm

  • 既水平又垂直get

    • 固定宽高

    • 不固定宽高

    • 使用 flexbox

水平居中

水平居中 inline 或者 inline-* 元素

你能够轻松的在一个 block 元素中水平居中一个 inline 元素,如下代码对 inlineinline-blockinline-tableinline-flex 等有效

.parent {
  text-align: center;
}

水平居中 block 类的元素

block 元素被设定固定宽度的状况下,能够使用设置元素 margin-leftmargin-right 的值为 auto 的方法实现水平居中。

.child {
  width: 400px;
  margin: 0 auto;
}

水平居中多个 block 类的元素

经过 inline-block实现

.parent {
  text-align: center;
}
.child {
  display: inline-block;
  text-align: left;
}

经过 flexbox 实现

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

垂直居中

垂直居中 inline 或者 inline-* 元素

单行

inline/text 元素能够简单的用设置相同的上下 padding 值达到垂直居中的目的。

.center {
  pading-top: 30px;
  padding-bottom: 30px;
}

若是由于某种缘由不能使用 padding 的方法,你还能够设置 line-height 等于 height来达到目的。

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

多行

相同的上下 padding 也能够适用于此种状况,若是不能生效,你能够尝试将该元素的父元素的 dispaly 设置为 table ,同时该元素的 dispaly 设置为 table-cell,而后设置 vertical-align

.parent {
  display: table;
  width: 200px;
  height: 400px;
}
.child {
  display: table-cell;
  vertical-align: middle;
}

若是上述方法不能使用,你能够尝试使用 flexbox,一个单独的 flexbox 子元素能够轻易的在其父元素中居中。谨记,这种方法须要父元素有固定的高度。

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

若是上述两种方式均不能使用,你能够使用“幽灵元素”技术,这种方法采用伪元素 ::before 撑开高度 ,文字垂直居中。

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

垂直居中 block 类的元素

已知元素高度

.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; */
}

未知元素高度

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

使用 flexbox

.parent {
  display: flex;
  flex-direction: column;
  justify-content: 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;
}
相关文章
相关标签/搜索