DIV水平垂直居中

 

<div class="father">
        <div class="son"></div>
</div>

方案一:通过父相子绝 自走父的50%再回走自身的一半

   .father {
            margin: 0 auto;
            width: 400px;
            height: 400px;
            background-color: black;
            position: relative;
        }
        
    .son {
            width: 100px;
            height: 100px;
            background-color: hotpink;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -50px;
            margin-top: -50px;
        }

方案二:通过父相子绝  子 margin: auto; top: 0;left: 0; right: 0;bottom: 0;

.father {
            margin: 0 auto;
            width: 400px;
            height: 400px;
            background-color: black;
            position: relative;
        }
        
.son {
            width: 100px;
            height: 100px;
            background-color: hotpink;
            position: absolute;
            margin: auto;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
        }

方案三:父相子绝 利用父的text-align实现子的居中 子需要转行内块 并回走自身一半

        .father {
            margin: 0 auto;
            width: 400px;
            height: 400px;
            background-color: black;
            position: relative;
            text-align: center;
           
        }
        
        .son {
            width: 100px;
            height: 100px;
            background-color: hotpink;
            display: inline-block;
            position: absolute;
            top: 50%;
            margin-left: -50px;
            margin-top: -50px;
        }

方案四:父相子绝 子走父50% 再过渡回自己的一半

        .father {
            margin: 0 auto;
            width: 400px;
            height: 400px;
            background-color: black;
            position: relative;
        }
        
        .son {
            width: 100px;
            height: 100px;
            background-color: hotpink;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

方案五:flex伸缩布局 主轴 副轴 都居中

        .father {
            margin: 0 auto;
            width: 400px;
            height: 400px;
            background-color: black;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        
        .son {
            width: 100px;
            height: 100px;
            background-color: hotpink;
        }

 

posted @ 2020-06-15 15:52  Fortuneteller  阅读(106)  评论(0编辑  收藏  举报