实现水平垂直居中的五种方法

来源:互联网 发布:java中replaceall 编辑:程序博客网 时间:2024/05/17 05:59

水平垂直居中

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

1. 定位 + margin 方法

  • 定位 + margin : auto;
.wrapper{    position:relative;    width:300px;    height:300px;    border:1px solid black;}.inner{    position:absolute;    top:0;    left:0;    bottom:0;    right:0;    width:100px;    height:100px;    background:orange;    margin:auto;}
  • 定位 + 负 margin
.wrapper{    position:relative;    width:300px;    height:300px;    border:1px solid black;}.inner{    position:absolute;    top:50%;    left:50%;    width:100px;    height:100px;    background:orange;    margin-top:-50px;    margin-left:-50px;}
  • 定位 + transform
.wrapper{    position:relative;    width:300px;    height:300px;    border:1px solid black;}.inner{    position:absolute;    top:50%;    left:50%;    width:100px;    height:100px;    background:orange;    transform:translate(-50%,-50%)}

2. 父元素 display:table-cell; 方法

.wrapper{    width:300px;    height:300px;    border:1px solid black;    display:table-cell;    vertical-align:middle;}.inner{    width:100px;    height:100px;    background:orange;    margin: 0 auto;}

3. flex 弹性盒子 方法

.wrapper{    width:300px;    height:300px;    border:1px solid black;    display:flex;    justify-content:center;    align-items:center;}.inner{    width:100px;    height:100px;    background:orange;}

4. inline-block + 伪元素 方法

.wrapper{    width:300px;    height:300px;    border:1px solid black;   text-align:center;}.wrapper::after{    content:'';    display:inline-block;    height:100%;    vertical-align:middle; }.inner{    width:100px;    height:100px;    background:orange;    display:inline-block;    vertical-align:middle;}

5. calc() + margin 方法

注意:运算符 - 或 + 两侧要加 空格

.wrapper{    width:300px;    height:300px;    border:1px solid black;}.inner{    width:100px;    height:100px;    background:orange;    margin:calc((100% - 100px)/2);}
原创粉丝点击