CSS水平垂直居中

(一)不知宽高

1、table
.c1{
  width: 500px;
  height: 300px;
  display: table;
}
.c2{
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

(二)定宽高

1、absolute + top + left + margin
.c1{
  width: 500px;
  height: 300px;
  position: relative;
}
.c2{
  position: absolute;
  width: 200px;
  height: 100px;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -100px;
}
2、absolute + top + right + left + bottom + margin: auto
.c2 {
  position: absolute;
  width: 200px;
  height: 200px;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

(三)定或不定宽高

1、flex
.c1{
  display: flex;
  align-items: center;
  justify-content: center;
}
2、absolute + top + left + trasform(translate)
.c1{
  width: 500px;
  height: 300px;
  position: relative;
}
.c2{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容