元素在盒子中垂直水平居中

<div class="box">
    <div class="ele"></div>
  </div>

1、position+margin

   .box{
     width: 600px;
     height:600px;
     margin:0 auto;
     border:solid 2px black;
     position:relative;
   }
   .ele{
     width: 20px;
     height:20px;
     background:pink;
     position:absolute;
     left:50%;
     top:50%;
     margin-left:-10px;
     margin-top:-10px;
   }
如果不清楚内部元素高度,上下左右都为0,margin:auto
.ele{
     width: 20px;
     height:20px;
     background:pink;
     position:absolute;
     top:0; left:0; right:0; bottom:0; margin: auto;
  }

2、position+transform

.box同上
.ele{
      width: 20px;
      height:20px;
      background:pink;
      position:absolute;
      left:50%;
      top:50%;
      transform: translate(-50%, -50%);
    }

3、flex布局
盒子 display:flex;justify-content: center; align-items: center;
4、如果元素是行内元素(不包含inline-block)
盒子 text-align:center,line-height:盒子高度

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。