当前位置: 代码迷 >> 综合 >> 如何将一个div水平垂直居中?4种方法做推荐
  详细解决方案

如何将一个div水平垂直居中?4种方法做推荐

热度:22   发布时间:2023-10-22 09:57:53.0

方案一:

div绝对定位水平垂直居中【margin:auto实现绝对定位元素的居中】,

兼容性:,IE7及之前版本不支持

    div{width: 200px;height: 200px;background: green; position:absolute;left:0;top: 0;bottom: 0;right: 0;margin: auto;}

 

方案二:

div绝对定位水平垂直居中【margin 负间距】     这或许是当前最流行的使用方法。

         div{width:200px;height: 200px;background:green;position: absolute;left:50%;top:50%;margin-left:-100px;margin-top:-100px;}        

 

方案三:

div绝对定位水平垂直居中【Transforms 变形】

兼容性:IE8不支持;

        div{width: 200px;height: 200px;background: green;position:absolute;left:50%;    /* 定位父级的50% */top:50%;transform: translate(-50%,-50%); /*自己的50% */}            

 

方案四:

css不定宽高水平垂直居中

     .box{height:600px;display:flex;justify-content:center;align-items:center;/* aa只要三句话就可以实现不定宽高水平垂直居中。 */}.box>div{background: green;width: 200px;height: 200px;}
  相关解决方案