美文网首页
常见的居中方式

常见的居中方式

作者: 1w1ng | 来源:发表于2017-08-13 22:02 被阅读0次

    1.text-align

    text-align: center;
    /*line-height: 100px;*/
    padding: 50px 0;
    

    2. 绝对定位实现居中

    position: absolute;
    top: 50%;
    left: 50%;
    /*margin-left: -100px;*/
    /*margin-top: -50px;*/
    transform: translate(-50%,-50%);
    }
    

    3. vertical-align实现居中

    .container {
      width: 600px;
      height: 400px;
      border: 1px solid;
      text-align: center;
    }
    
    .container::before {
      content: '';
      display: inline-block;
      height: 100%;
      vertical-align: middle;
    }
    
    image.png

    4. table-cell实现居中

    .container {
      width: 600px;
      height: 400px;
      border: 1px solid ;
      display: table-cell;
      vertical-align: middle;
      text-align: center;
    }
    

    实现效果和vertical-align一样。

    5. display: flex

    .container {
      width: 100vw;
      height: 100vh;  /* 设置宽高以显示居中效果 */
      display: flex;  /* 弹性布局 */
      align-items: center;  /* 垂直居中 */
      justify-content: center;  /* 水平居中 */
    }
    
    body {
      margin: 0;
      background: rgba(0, 0, 0, .95);
    }
    
    .container::after {
      content: '🌏';
      font-size: 85px;
    }
    
    .container::before {
      content: '🌏';
      font-size: 85px;
    }
    
    image.png

    最终实现元素垂直水平居中

    相关文章

      网友评论

          本文标题:常见的居中方式

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