怎样使盒子上下左右居中

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

怎样使盒子上下左右居中_第1张图片

方法一

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

 
    #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; }
        

怎样使盒子上下左右居中_第2张图片

你可能感兴趣的:(css,html)