CSS之绝对定位的位置以及子元素在父容器的居中显示

元素开启了绝对定位:
水平布局:
left+margin-left+border-left+padding-left+width+padding-right+border-right+margin-right+right
=包含块的宽度

此时规则和之前一样,只是多了left和right这两个值
当发生过度约束:
如果9个值没有auto,则自动调整right值以使等式成立
如果有auto,则自动调整auto值以使等式成立

可设置auto的值:
margin width left right

垂直方向布局也必须满足等式:
topt+margin-top+border-top+padding-top+height+padding-bottom+border-bottom++margin-bottom+bottom
=包含块的高度

通过以上规则,可以实现使得子元素在父容器中居中显示(水平方向和垂直方向)``

Demo:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>绝对定位元素的位置</title>
    <style>
        .box1{
            width:500px;
            height:500px;
            background-color:#bfa;

            /* 父元素开启相对定位 */
            position: relative;
        }

        .box2{
            width:100px;
            height:100px;
            background-color:orange;

            /*设置水平居中显示 */
            /* margin-left:auto;
            margin-right:auto;  */

            /* 设置垂直方向垂直居中显示 */
            /* margin-top:auto;
            margin-bottom:auto; */


            /* 设置水平方向和垂直方向居中显示 */
            margin: auto;

            /* 开启绝对定位 */
            position: absolute;
            /* 
            left和right的默认值为auto,所以如果不设置这两个值
            则等式不满足时,会自动调整这两个值(必须设置)           
            */
            /* (水平方向)将子元素置父元素左上角处 */

            left:0;
            right:0;


            top:0;
            bottom:0;
        }
    </style>
</head>
<body>
    <div class="box1">
        <div class="box2"></div>
    </div>
    
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值