首页 > 代码库 > 多种方式垂直水平居中

多种方式垂直水平居中

1. 不需要知道父容器和子容器的具体尺寸

 (1)方法一:margin

 <div class="wrapper">        <div class="content"></div>    </div>

 

.wrapper {    display: table-cell;    width: 500px;    height: 500px;    text-align: center; /*水平居中*/    border: 1px solid #eee;    vertical-align: middle; /*图片垂直居中*/    position: relative;    } .content {    width: 200px;    height: 200px;    background-color: red;    margin: auto;}

 

   (2)方法二:绝对定位 + transform, 应用到了css3知识,需要注意兼容性问题

<div class="wrapper">        <div class="content"></div>    </div>

 

.wrapper {    display: table-cell;    width: 500px;    height: 500px;    text-align: center; /*水平居中*/    border: 1px solid #eee;    vertical-align: middle; /*图片垂直居中*/    position: relative;    } .content {    width: 200px;    height: 200px;    background-color: red;    position: absolute;    left: 50%;    right: 50%;   transform: translate(-50%, -50%);}

 

  (3)flex弹性盒子,应用到了css3知识,需要注意兼容性问题

<div class="wrapper">        <div class="content"></div>    </div>

 

 

.wrapper {    width: 500px;    height: 500px;    border: 1px solid #eee;    display:flex;    justify-content:center;    align-items: center;  } .content {    width: 200px;    height: 200px;    background-color: red;}

 


 

2.已知宽高尺寸

<div class="wrapper">        <div class="content"></div>    </div>

 

.wrapper {    width: 500px;    height: 500px;    border: 1px solid #eee;    position: relative;} .content {    width: 200px;    height: 200px;    background-color: red;    position: absolute;    left: 50%;    top: 50%;    /*自身宽高一半的负值*/    margin-left: -100px;    margin-top: -100px;}

 

多种方式垂直水平居中