1. 程式人生 > >div 水平垂直居中

div 水平垂直居中

nta isp right posit true ems container sla play

已知布局為如下:

<div id="container">
    <p>test</p>
    <div id="center">12345</div>
</div>

不知道寬和高的情況下:

方法一:

#container{
            position:relative;
            background:blue;
        }
        #center{
            background:red;
            position:absolute;
            left:50%;
            top:50%;
            transform:translate(-50%,-50%);   //translate 是基於元素自身的尺寸來計算的
        }

方法二:

<div id="container">
    <!--<p>test</p>-->
    <div id="center">12345</div>
</div>

        #container{
            display:flex;
            align-items: center;
            justify-content: center;
            background:blue;
        }
        #center{
            background:red;
        }  

固定寬和高

        #container{
            position:relative;
            width:300px;
            height:300px;
            background:blue;
        }
        #center{
            width:100px;
            height:100px;
            background:red;
            position:absolute;
            left:50%;
            top:50%;
            margin-top:-50px;
            margin-left:-50px;
        }

方法二

        #container{
            position:relative;
            width:300px;
            height:300px;
            background:blue;
        }
        #center{
            width:100px;
            height:100px;
            background:red;
            position:absolute;
            margin:auto;
            left:0;
            top:0;
            right:0;
            bottom:0;
        }

  

div 水平垂直居中