水平垂直居中

626 阅读1分钟

1.div固定宽高

如果想要写一个居中于整个页面的,比如弹框呀,loading图等

html
<div class="loading></div>"
css
.loading{
      width:100px;
      height: 100px;
      background-color:red;
      position:absolute;
      left:0;
      top:0;
      bottom:0;
      right:0;
      margin:auto;
}
如果是基于某个div中的
html
<div class="wrapper">
    <div class="loading"></div>
</div>
css
在wrapper上增加position:relative;
.wrapper{
  width:200px;
  height: 200px;
  background-color: green;
  position:relative;
}
.circle{
  width:100px;
  height: 100px;
  background-color:red;
  position:absolute;
  left:0;
  top:0;
  bottom:0;
  right:0;
  margin:auto;
}

2.外部容器固定宽高

html
<div class="out">
    <div class="inner"></div>
</div> 
css
.out{
    width: 500px;
    height: 500px;
    display:flex;
    justify-content: center;
    align-items: center;
}
.inner{width: 200px;height: 200px;}
  1. 利用宽高的一半来实现居中

    html

    
     <div class="wrap center">
        <div class="center2"></div>
     </div>
     
    

    css

    .wrap {
      width: 100px;
      height: 100px;
      background-color: red;
      position: relative;
    }
    .center2 {
      width: 50px;
      height: 50px;
      background-color: green;
      position: absolute;
      left: 50%;
      top: 50%;
      margin-left: -25px;
      margin-top: -25px; 
      //以上两行也可以改成transform的写法:
      transform: translateX(-50%) translateY(-50%);
    }