CSS实现元素水平垂直居中几种方案

方案一:利用 display: inline-block; vertical-align: middle;

   

    

.box {

  width: 500px;

  height: 500px;

  background-color: red;

  text-align: center;

}

.box div {

  width: 200px;

  height: 200px;

  background-color: orange;

  display: inline-block;

  vertical-align: middle;

}

.box span {

  width: 0;

  height: 100%;

  display: inline-block;

  vertical-align: middle;

}

方案二:定位法(1)

      

.box {

  width: 500px;

  height: 500px;

  background-color: red;

  position: relative;

}

.box div {

  width: 200px;

  height: 200px;

  background-color: orange;

  position: absolute;

  top: 0;

  bottom: 0;

  left: 0;

  right: 0;

  margin: auto;

}

 方案三:定位法(2)

      

.box {

  width: 500px;

  height: 500px;

  background-color: red;

  position: relative;

}

.box div {

  width: 200px;

  height: 200px;

  background-color: orange;

  position: absolute;

  left: 50%;

  top: 50%;

  margin-left: -100px;

  margin-top: -100px;

}

方案四: 弹性布局

      

.box {

  width: 500px;

  height: 500px;

  background-color: red;

  display: flex;

  justify-content: center;

  align-items: center;

}

.box div {

  width: 200px;

  height: 200px;

  background-color: orange;

}

方案五:利用 display: table-cell; vertical-align: middle; 

      

.box {

  width: 500px;

  height: 500px;

  background-color: red;

  display: table-cell;

  vertical-align: middle;

  text-align: center;

}

.box div {

  width: 200px;

  height: 200px;

  background-color: orange;

  display: inline-block;

}

方案六:利用translate位移

      

.box {

  width: 500px;

  height: 500px;

  background-color: red;

  position: relative;

}

.box div {

  width: 200px;

  height: 200px;

  background-color: orange;

  position: absolute;

  top: 50%;

  left: 50%;

  transform: translate(-50%,-50%);

}

效果图如下:

 

CSS实现元素水平垂直居中几种方案_第1张图片

你可能感兴趣的:(css,前端,html,vue.js,css3)