CSS 盒子垂直居中常见的几种方式

102 阅读1分钟

盒子垂直居中在实际开发项目中是很常见的布局,实现有以下几种方式

  • position + margin
  • position + transform
  • flex布局

1. position + margin布局

这种布局方式只适合width/height有固定值的时候

<div id="main"></div>

<style>
  #main{
    position: absolute;
    top: 50%;
    left: 50%;
    width: 300px;
    height: 300px;
    margin: -150px 0 0 -150px;
    background: pink;
  }
</style>

2. position + transform布局

此布局width/height没有固定值也可以实现居中

<div id="main">
   这是盒子里的内容,用来撑开盒子宽高的
</div>

<style>
  #main{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    font-size: 30px;
    color: #fff;
    background: pink;
  }

3. flex布局

<div id="main">
   <span>我是span标签里的内容</span>
</div>

<style>
  #main{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 300px;
    height: 300px;
    border: 1px solid red;
  }
  #main span{
    font-size: 30px;
    color: #fff;
    background: pink;
  }

以上就是最常见的几种水平垂直居中的方式,当然了,flex布局是最简单的了,如果你要兼容IE低版本浏览器,就只能老老实实的用常规的写法了