首页 > 代码库 > 让一个元素在容器中垂直居中的几个方法

让一个元素在容器中垂直居中的几个方法

  1. 方法一,使用js让元素水平垂直居中
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #box{
                height:200px;
                width:200px;
                background:deeppink;
                position:absolute;    
            }
        </style>
    </head>
    <body>
        <div id="box"></div>
        <script type="text/javascript">
            var box=document.getElementById("box");
            var l=document.documentElement.clientWidth/2-box.offsetWidth/2;
            var t=document.documentElement.clientHeight/2-box.offsetHeight/2;
            box.style.top=t+‘px‘;
            box.style.left=l+‘px‘;
            

        </script>
    </body>
</html>
                        

  2.使用position属性使元素水平垂直居中

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #box{
                height:200px;
                width:200px;
                background:deeppink;
                position:absolute;
                top:50%;
                left:50%;
                margin:-100px 0 0 -100px;
            } 
        </style>
    </head>
    <body>
        <div id="box"></div>
    </body>
</html>

  3.使用弹性盒模型方法

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #box1{
                height:200px;
                width:200px;
                display: flex;
                background: deeppink;
            }
            #box2{
                margin:auto;
                width:50px;
                height:50px;
                background: deepskyblue;
                margin:auto;
            }
        </style>
    </head>
    <body>
        <div id="box1">
            <div id="box2"></div>
        </div>
    </body>
</html>

 

  

让一个元素在容器中垂直居中的几个方法