水平垂直居中

水平垂直居中

<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>

猜你喜欢

转载自www.cnblogs.com/haoluck/p/9226764.html
今日推荐