绝对定位元素的位置

 <style>
        .box1{
            width: 600px;
            height: 600px;
            background-color: #bfa;
            position: relative ;
        }
        .box2{
            width: 100px;
            height: 100px;
            background-color: tomato;
            position: absolute ;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            /*
            水平布局:
                left + margin-left + border-left + padding-left + width + padding-right + border-right + margin-right + right
            -当我们开启了绝对定位后:
                水平方向的布局等式就需要多加两个值:left right
                    此时规则和之前一样只是多加了两个值:
                        当发生过度约束:
                            如果九个值中没有 auto 则自动调整 right 以使等式满足
                            如果有auto,则自动调整 auto 的值以使等式满足    
            -可设置的auto的值:
                margin width left right
           
            -因为 left和 right 的默认值是 auto,所以如果不知道 left和right
             则等式不满足时,会自动调整他们的值
           
             垂直方向的布局的等式也要满足:
                top + margin-top/bottom + padding-top/bottom + height + top +bottom
               
           
                            */
       
        }



    </style>
</head>
 
 
<body>
    <div class="box1">
        <div class="box2"></div>
    </div>
</body>
 
根据绝对定位,可以得到一个使子元素垂直水平居中的办法,既代码中绿色部分,将 top,bottolm,left,right 设置为 0,margin 设置为auto
但别忘记 absolute 是参考包含块进行定位的,所以父元素需要开启定位,如 relative
 
posted @   故渊ccx  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示