美文网首页
CSS水平垂直居中

CSS水平垂直居中

作者: 摸摸大海参 | 来源:发表于2019-04-27 16:13 被阅读0次

(一)不知宽高

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%);
}

相关文章

网友评论

      本文标题:CSS水平垂直居中

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