欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CSS+HTML的div怎么居中

程序员文章站 2022-05-02 09:49:37
...
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>子元素在父元素中水平垂直居中</title>
    <style>
        /*
        1.内容水平居中
        text-align:center;
        2.盒子水平居中
        div{
            width:200px;
            margin:0 auto;
        }

        3.一行位置垂直居中
        line-height=height

        3.多个内容垂直居中
        父元素加padding(上下padding值一样)


        4.子元素在父元素中水平垂直居中
        1)弹性盒

        .partent{
            width: 500px;
            height: 500px;
            background-color: red;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .child{
            width: 200px;
            height: 200px;
            background-color: pink;
        }

        2)表格法
         .partent{
            width: 500px;
            height: 500px;
            background-color: red;
            display: table-cell;
            vertical-align: middle;
        }
        .child{
            width: 200px;
            height: 200px;
            background-color: pink;
            margin: 0 auto;
        }

        3.外边距
         .partent{
            width: 500px;
            height: 500px;
            background-color: red;
            overflow: hidden;
        }
        .child{
            width: 200px;
            height: 200px;
            background-color: pink;
            margin: 0 auto;
            margin-top: 150px;
        }

        4.绝对定位法
         .partent{
            width: 500px;
            height: 500px;
            background-color: red;
            position: relative;
        }
        .child{
            width: 200px;
            height: 200px;
            background-color: pink;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -100px;
        }








        */
        .partent{
            width: 500px;
            height: 500px;
            background-color: red;
            position: relative;
        }
        .child{
            width: 200px;
            height: 200px;
            background-color: pink;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -100px;
        }
    </style>
</head>
<body>
<div class="partent">
    <div class="child"></div>
</div>
</body>
</html>