A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 剑枫dj 初级黑马   /  2019-10-14 23:28  /  610 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

Css中 子级div盒子在父级盒子垂直居中的三个方法

实际网页开发中,要实现同样的效果,不同的开发者会用不同的方式搭建,初学者若熟练使用各种方法,后续学习自然会事半功倍。现总结3种div垂直居中的方法供各位参考。
方法一、小div绝对定位或相对定位,这样小div脱离标准流,大div有固定宽高,用小div的margin去挤大div
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .father {
            width: 600px;
            height: 600px;
            background-color: orangered;
        }
        
        .son {
            width: 300px;
            height: 200px;
            background-color: lawngreen;
            position: absolute;
            margin: 200px 150px;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son""></div>
    </div>
</body>
</html>

注意:如果小div没有绝对定位或相对定位,且大div没有border,那么小div的margin实际上踹的是“流”,踹的是这“行”。如果用margin-top,大div整体也会掉下来。
方法二、如果给大div加一个border,使大div,小div都不定位,用小div的margin去挤大div,实现小div居中。
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .father {
            width: 600px;
            height: 600px;
            background-color: orangered;
            border: 1px solid white;
        }
        
        .son {
            width: 300px;
            height: 200px;
            background-color: lawngreen;
            margin: 200px 150px;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>
</html>

方法三、小div绝对定位,大div相对定位,定位到大盒子的宽高一半的位置,再上下各margin负的自己宽高的一半
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .father {
            width: 600px;
            height: 600px;
            background-color: orangered;
            position: relative;
        }
        
        .son {
            width: 300px;
            height: 200px;
            background-color: lawngreen;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -100px;
            margin-left: -150px;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>
</html>


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马