美文网首页我爱编程
CSS中的常见居中布局

CSS中的常见居中布局

作者: ProgrameLin | 来源:发表于2018-04-14 20:13 被阅读0次

    1. 水平居中

    第一种: margin-left 和 margin-right auto
    <div class='test'>
      </div>
    
    
    设定好宽度和高度后, 左右为间距为auto的时候就可以实现水平居中
    .test {
      border: 1px solid red;
      width: 100px;
      height: 100px;
      margin-left: auto;
      margin-right: auto;
    }
    
    第二种: flex布局
    .test {
      border: 1px solid red;
      width: 100px;
      height: 100px;
      
    }
    
    body {
      display: flex;
      justify-content: center;
    }
    

    2. 垂直居中

    
    <div class='test'>
      </div>
    
    第一种: 绝对定位
    .test {
      border: 1px solid red;
      width: 100px;
      height: 100px;
      position: absolute;
      top: 50%;
      left: 50%;
      margin:-50px 0 0 -50px;
    }
    
    第二种: 绝对定位+margin 
    .test {
      border: 1px solid red;
      width: 100px;
      height: 100px;
      position: absolute;
      margin: auto;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
    }
    
    

    3. 文字居中

    水平居中
    text-align: center;
    
    垂直居中
    height: 30px;
    line-height: 30px;
      设置完line-height后文字的大小没有改变, 只是文字的上间距和下间距发生了变化
      让文字看上去就是垂直居中
    
    
    使用flex去做, 只需要在父容器中添加
    display: flex;
    justify-content: center;
    align-items: center;
    

    相关文章

      网友评论

        本文标题:CSS中的常见居中布局

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