css垂直居中

css垂直居中方法小结,日后可能会有更新:

height与line-height相等让单行内联元素垂直居中此处略过。

其他内联元素的垂直居中此处暂且不谈。以下讨论的都是块状元素的垂直居中方式

1、绝对定位+负margin:

利用绝对定位将元素移动,再回拉自身的一半:

html:

<div class="father">
  <div class="child"></div>
</div>

 

css:

.father{
  position: relative;
  height: 300px;
  background-color: lightblue;
}
.child {
  width:100px;
  height:100px;
  position: absolute;
  top:50%;
  left: 50%;
  margin-top:-50px;
  margin-left: -50px;
  background: green;
}

 

效果图:

 

缺点:需要知道元素自身的宽高

2、绝对定位 + translate(css3属性,对兼容性要求较高)

方法跟第一种类似,只不过将负margin变成了translate,不过可以不需要知道元素的宽高了

只要将上面的负margin换成下面代码即可:

  transform: translate(-50%,-50%);

3、绝对定位 + margin : auto

css代码:

.father{
  position: relative;
  height: 300px;
  background-color: lightblue;
}
.child {
  width:100px;
  height:100px;
  position: absolute;
  top:0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  background: green;
}

实现原理的话可以去看一下张鑫旭的博客。

4、flex + margin: auto

将父元素的display设置为flex后,用margin: auto即可完成水平垂直居中(用了flex,自然pc的兼容性不太良好)

css:

.father{
  display: flex;
  height: 300px;
  background-color: lightblue;
}
.child {
  width:100px;
  height:100px;
  margin: auto;
  background: green;
}

5、 flex

单纯应用flex及它的一些属性:

css:

.father{
  display: flex;
  height: 300px;
  justify-content:center;
  align-items: center;
  background-color: lightblue;
}
.child {
  width:100px;
  height:100px;
  background: green;
}

 

6、利用伪元素 + vertical-align:middle

css代码:

.father {
  height: 300px;
  text-align: center;
  background-color: lightblue;
}
.child {
  width:100px;
  height:100px;
  display: inline-block;
  vertical-align: middle;
  background: green;
}
.father:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

7、利用table元素的自带居中特性:

在father外面再套一层table,把father当成是td,就可以设置它的vertical-align进行居中了,然后再在里面填内容。

html:

<div class="table">
    <div class="father">
      <div class="child"></div>
    </div>
  </div>

css:

.table{
  display:table;
}
.father {
  display: table-cell;
  vertical-align: middle;
  height: 300px;
  background-color: lightblue;
}
.child {
  width:100px;
  height:100px;
  background: green;
}

此处只完成了垂直居中,如果父类设置了宽度的话,子类的水平居中可采用margin: 0 auto实现。

 

posted @ 2018-04-18 00:06  calmbook  阅读(176)  评论(0编辑  收藏  举报