美文网首页
CSS居中问题总结

CSS居中问题总结

作者: 沉默紀哖呮肯伱酔 | 来源:发表于2020-12-03 10:56 被阅读0次

    1、居中元素宽高固定

    • 绝对定位+margin
    // top和left 为 50%, margin的left和top为自身宽高一半
    .center {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -height/2;
      margin-top: -width/2;
    }
    
    • 绝对定位+calc
    .center {
      position: absolute;
      top: calc(50% - height/2);
      left: calc(50% - width/2);
    }
    

    2、被居中元素宽高不定

    • transform变换
    .center {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    
    • flex+auto
    .parent {
      display: flex;
    }
    .center {
      margin: auto;
    }
    
    • flex
    .parent{
      display: flex;
      align-items: center;
      justify-content: center;
    }
    

    相关文章

      网友评论

          本文标题:CSS居中问题总结

          本文链接:https://www.haomeiwen.com/subject/bkcmwktx.html