怎样使盒子上下左右居中

♀尐吖头ヾ 提交于 2020-03-01 05:23:03

普通的margin:auto 是无法使盒子上下居中的,于是有了一下的解决方案

在这里插入图片描述

方法一

使用定位百分比居中,再拉取一半

 
    #box1{ width:300px; height: 300px; border:1px black solid; position: relative;}
    #box2{ width:100px; height:100px; background:red; position: absolute;
        left:50%; top:50%; margin:-50px;} 
        

这样可以做到,但是box2需要固定大小

方法二

利用translate,
因为margin的百分比是按照box1来计算的
translate的百分比是按照box2来计算的
这种模式非常适合box2不是固定大小的情况。


    #box1{ width:300px; height: 300px; border:1px black solid; position: relative;}
    #box2{ width:200px; height:100px; background:red; position: absolute;
        left:50%; top:50%; transform: translate(-50%,-50%);

方法三

在弹性盒子中,margin:auto;会让上下左右都生效。


    #box1{ width:300px; height: 300px; border:1px black solid; display: flex;}
    #box2{ width:200px; height:100px; background:red; margin:auto; }
        

在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!