美文网首页
CSS居中布局方案

CSS居中布局方案

作者: 菲利普马洛 | 来源:发表于2018-09-24 15:47 被阅读28次

    水平居中

    /* solution1 */
    .parent {
      text-align: center;
    }
    .child {
      display: inline-block;
    }
    
    /* soluction2 */
    .child {
      display: table;
      margin: 0 auto;
    }
    
    /* solution3 */
    .parent {
      position: relative;
    }
    .child {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
    
    /* solution4 */
    .parent {
      display: flex;
      justify-content: center;
    }
    
    

    垂直居中

    /* solution1 */
    .parent {
      display: table-cell;
      vertical-align: middle;    
    }
    
    /* solution2 */
    .parent {
      position: relative;
    }
    .child { 
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
    
    /* solution3 */
    .parent {
      display: flex;
      align-items: center;
    }
    
    /* solution4 */
    .parent {
      height: 300px;
      writing-mode: vertical-lr;
    }
    .child {
      height: 100px;
      margin: auto;
    }
    

    水平垂直居中

    /* solution1 */
    .parent {
      display: table-cell;
      text-align: center;
      vertical-align: middle;
    }
    .child {
      display: inline-block;
    }
    
    /* solution2 */
    .parent {
      position: relative;     
    }
    .child {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    
    /* solution3 */
    .parent {
      display: flex;
      justify-content: center;
      align-items: center;   
    }
    
    /* solution4 */
    .parent {
      width: 300px;
      height: 150px;
      position: relative;
    }
    .child {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      width: 50px;
      height: 50px;
      margin: auto;
    }
    
    

    相关文章

      网友评论

          本文标题:CSS居中布局方案

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