水平居中和垂直居中

  本文列举了水平和垂直居中的方法,分别在已知宽高和未知宽高的情况。

从以下方法不难看出,要制造居中,大体分为位移居中和直接设置居中。

html

<div class="farther">

<div class="son"></div>

</div>

4个方法

已知宽高:

1.定位+margin

.father {

      width: 500px;

      height: 500px;

      background: #ccc;

      position: relative;

    }

    .son {

      width: 200px;

      height: 200px;

      background: orange;

      position: absolute;

      top: 50%;

      left: 50%;

      margin-left: -100px;

      margin-top: -100px;

    }

2..定位+calc

.father {

      width: 500px;

      height: 500px;

      background: #ccc;

      position: relative;

    }

.son {

      width: 200px;

      height: 200px;

      background: orange;

      position: absolute;

      top:( 50%-100px);

      left: calc(50%-100px);   

    }

3.定位+制造位移

.father {

      width: 500px;

      height: 500px;

      background: #ccc;

      position: relative;

    }

.son {

      width: 200px;

      height: 200px;

      background: orange;

      position: absolute;

    transform: translate(-50%,-50%)

    }

*****忘了******

4.diplay:flex

.father {

      width: 500px;

      height: 500px;

      background: #ccc;

display:flex;

justify-content: center;

align-items: center;

    }

.son {

      width: 200px;

      height: 200px;

      background: orange;

    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容