CSS Center(居中专题)

2022-07-25,,,

CSS Center(居中专题

水平居中(左右居中)

// 1.inline-block + text-align
    .parent{
        text-align: center;
    }
    .child{
        display: inline-block;
    }
    // tips:此方案兼容性较好,可兼容至IE8,对于IE5 6 7并不支持inline-block,需要使用css hack进行兼容
// 2.table + margin
    .child{
        display: table;
        margin: 0 auto;
    }
    // tips:此方案兼容至IE8,可以使用<table/>代替css写法,兼容性良好
// 3. absolute + transform
    .parent {
        position: relative;    
        height: 1.5em;
    }
    .child {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
    }
    // tips:此方案兼容至IE9,因为transform兼容性限制,如果.child为定宽元素,可以使用以下写法,兼容性极佳
    .parent{
        position: relative;
        height:1.5em;
    }
    .child{
        position: absolute;
        width:100px;
        left: 50%;
        margin-left:-50px;
    }
//4. flex + justify-content
    .parent {
        display: flex;
        justify-content: center;
    }
    .child {
        margin: 0 auto;
    }

竖直居中(上下居中)

//1.table-cell + vertial-align
    .parent{
        display: table-cell;
        vertical-align: middle;
    }
//2.absolute + transform
    .parent{
        position: relative;
    }
    .child{
        position: absolute;
        top: 50%;`在这里插入代码片`
        transform: translateY(-50%);
    }
//tips:存在css3兼容问题,定宽兼容性良好
// tips: safari浏览器显示异常,不建议使用
//3.flex + align-items
    .parent{
        display: flex;
        align-items: center;
    }
//tips:高版本浏览器兼容,低版本不适用

水平垂直居中(上下左右居中)

//1.inline-block + table-cell + text-align + vertical-align
    .parent{
        text-align: center;
        display: table-cell;
        vertical-align: middle;
    }
    .child{
        display: inline-block;
    }
// tips:兼容至IE8
//2.absolute + transform
    .parent{
        position: relative;
    }
    .child{
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
    }
// 像素为 奇数时,会出现字体模糊
//3.flex
    .parent{
        display: flex;
        justify-content: center;
        align-items: center;
    }
// 4
  .demo1 {
    display: flex;
    .cont {
      margin: auto;
    }
  }
// 5
   .parent{
      position: relative;
   }
   .child{
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
   }

本文地址:https://blog.csdn.net/SeriousLose/article/details/111916594

《CSS Center(居中专题).doc》

下载本文的Word格式文档,以方便收藏与打印。