CSS水平垂直居中

2019-04-27  本文已影响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%);
}
上一篇 下一篇

猜你喜欢

热点阅读