div盒子水平居垂直中的几种方法

时间:2024-08-07 00:05:26
div盒子水平居垂直中的几种方法
<!DOCTYPE html>
<html>
    <head>
        <mete charset="utf-8"/>
        <style>
            *{
                margin: 0;
                padding: 0;
            }
            /*方案1、使用transforms属性的translate平移*/
            .div1{
                position: absolute;
                width: 500px;
                height: 500px;
                border: 1px solid #000;
                left: 50%;
                top: 50%;
                transform: translate(-50%,-50%);
              
            }
            .div2{
                position: absolute;
                width: 250px;
                height: 300px;
                border: 1px solid#000;
                left: 0;
                right: 0;
                top: 0;
                bottom: 0;
                margin: auto;
            }
            margin 负间距
/*
1.必需知道该div的宽度和高度,
2.然后设置位置为绝对位置,
3.距离页面窗口左边框和上边框的距离设置为50%,这个50%就是指盒子左上角顶点距离页面左、上边界的50%,
4.最后将该div分别左移和上移,使整个盒子居中,左移和上移的大小就是该DIV(包括border和padding)宽度和高度的一半。
*/
            .div3{
                position: absolute;
                width: 100px;
                height: 50px;
                border: 1px solid#000;
                margin-top: -26px;
                margin-left: -51px;
                left: 50%;
                top: 50%;
            }
        </style>
    </head>
    <body>
        <div class="div1"></div>
        <div class="div2"></div>
        <div class="div3"></div>
    </body>
</html>