水平垂直居中

水平垂直居中

<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>
-----------------------------------------------------------------------
        分割线
-----------------------------------------------------------------------
<!-- 还有一种可能遇到的居中效果,浮动居中 -->
<style>
        .box {
            background-color: #FF8C00;
            clear: left; 
            float: left;  
            position: relative;
            left: 50%;
        }
        .content {
            background-color: #F00;
            width: 100px;
            height: 100px;
            position: relative;
            float: left;
            right:50%;
        }
</style>
posted @ 2018-06-25 22:50  撑船的摆渡人  阅读(110)  评论(0编辑  收藏  举报