水平垂直居中

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

/*position 元素已知宽度*/
<style>
    .box {
        background-color: #FF8C00;
        width: 300px;
        height: 300px;
        position: relative;
    }
    .content {
        background-color: #F00;
        width: 100px;
        height: 100px;
        position: absolute;
        left: 50%;
        top: 50%;
        margin: -50px 0 0 -50px;
    }
</style>

<style>
    .box {
        background-color: #FF8C00;
        width: 300px;
        height: 300px;
        position:relative;
    }
    .content {
        background-color: #F00;
        width: 100px;
        height: 100px;
        position: absolute;
        top:0;
        left:0;
        bottom:0;
        right:0;
        margin:auto;
    }
</style>

/*position transform*/
<!--可能在有些设备中会存在差了半像素的情况-->
<style>
    .box {
        background-color: #FF8C00;
        width: 300px;
        height: 300px;
        position: relative;
    }
    .content {
        background-color: #F00;
        width: 100px;
        height: 100px;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
    }
</style>

/*flex布局*/
<style>
    .box {
        background-color: #FF8C00;
        width: 300px;
        height: 300px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .content {
        background-color: #F00;
        width: 100px;
        height: 100px;
    }
</style>

版权声明:本文为haoluck原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/haoluck/p/9226764.html