美文网首页
CSS居中的几种方法

CSS居中的几种方法

作者: 蛮吉大人123 | 来源:发表于2018-06-20 15:57 被阅读46次
    1. line-height 适用于单行文本
    .box {
      height: 3em;
      line-height: 3em;
    }
    
    1. vertical-align: middle
    .pic_box {
     width: 300px;
     hieght: 300px;
     font-size: 0;
    }
    .pic_box img {
     vertical-align: middle;
    }
    
    .pic_box:after {
     display: inline-block;
     width: 0;
     height: 100%;
     content: '';
     vertical-align: middle;
     overflow: hidden;
    }
    

    注意需要两个同级的inline/inline-block元素vertical-align: middle才能起到真正的居中效果

    1. display: table-cell
    .pic_box {
      width: 300px;
      height: 300px;
      background-color: #beceeb;
      display: table-cell;
      text-align: center;
      vertical-align: middle;
    }
    
    1. 绝对定位 + margin 1.0
    .content {
      position: absolute;
      top: 50%;
      left:50%;
      width: 240px;
      margin-left: -120px;/* 目标元素的宽度的一半 */
      height: 240px;
      margin-top: -120px; /* 目标元素的高度的一半 */
    }
    

    此方法只适用于固定大小的元素

    1. 绝对定位 + margin 2.0
    #content {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      height: 240px;
      width: 70%;
    }
    
    1. 绝对定位 + transform
    .inner{
      position : absolute;
      top: 50%;
      left:50%;
      -webkit-transform: translate(-50%,-50%);
      -moz-transform: translate(-50%,-50%);
      -ms-transform: translate(-50%,-50%);
      -o-transform: translate(-50%,-50%);
      transform: translate(-50%,-50%);
    }
    
    1. display: flex;
    .box{
      display: flex;
      align-items:center;
    }
    
    1. 浮动元素水平居中的方法
      让最外面的浮动层相对定位,left等于50%,然后内部嵌套层也使用相对定位且left设为-50%,这样的效果就是内层相对整行为水平居中


      图片.png

    相关文章

      网友评论

          本文标题:CSS居中的几种方法

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