一个div上下左右居中

//已知宽高的1
.wrap {
  width: 300px;
  height: 300px;
  background-color: red;
  position: absolute;//或者/fixed
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}
//已知宽高的2.1
.wrap{
    width: 300px;
    height: 300px;
    background-color: red;
    position: absolute;
    top: 50%;
    margin-top: -150px;
    left: 50%;
    margin-left: -150px;
}
//未知宽高的,靠内容撑的2.2
.wrap{
    background-color: red;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
//父元素flex布局的,3
body{
    display: flex;
    align-items: center;
    justify-content: center;
}

.wrap {
  width: 300px;
  height: 300px;
  background-color: red;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容