CSS(3)实现水平垂直居中

方法一:

div{
    position: absolute;
    /*position: fixed 也可以*/
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 100px;
    height: 100px;
    margin: auto;
    background-color: green;
}
<div></div>

方法二:

div{
    position: absolute;
    /*position: fixed 也可以*/
    left: 50%;
    top: 50%;
    width: 100px;
    height: 100px;
    margin-left: -50px;
    margin-top: -50px;
    background-color: red;
}
<div></div>

方法三:

div{
    position: absolute;
    /*position: fixed 也可以*/
    left: 50%;
    top: 50%;
    width: 100px;
    height: 100px;
    transform: translate(-50%,-50%);
    background-color: green;
}
<div></div>

方法四:

body{
    display: flex;
    justify-content: center;/*使内容水平居中*/
    align-items: center;/*使内容垂直居中*/
}
div{
    width: 100px;
    height: 100px;
    background-color: green;
}
<div></div>

方法五:

div{
    position: absolute;
    left: calc((100%-100px)/2);
    top: calc((100%-100px)/2);
    width: 100px;
    height: 100px;
    background-color: red;
}
<div></div>

方法六:

.table{
    display: table;/*此元素会作为块级表格来显示(类似 <table>),表格前后带有换行符*/
    width: 100%;
    height: 100%;            
}
.ok{
    display: table-cell;/*此元素会作为一个表格单元格显示(类似 <td> 和 <th>)*/
    text-align: center;/*水平居中*/
    vertical-align: middle;/*垂直居中*/
}
.innerBox{
    display: inline-block;
    width: 100px;
    height: 100px;
    background-color: red;
}
<div class='table'>
    <div class='ok'>
        <div class='innerBox'></div>
    </div>
</div>

猜你喜欢

转载自www.cnblogs.com/fuyinjuan/p/9016987.html