利用定位让子盒子在父盒子里面水平和垂直居中的三种小方法

76 阅读1分钟

利用定位让子盒子在父盒子里面水平和垂直居中的三种小方法

1.设置好子相父绝

 .box {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 100px;
  background-color: skyblue;
  transform: translate(-50%, -50%);
  }

2.设置好子相父绝

  .box {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top:-100px;
  margin-left:-100px;
  width: 200px;
  height: 200px;
  background-color: skyblue;
  }

3.设置好子相父绝

  .box { 
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  width: 200px;
  height: 200px;
  background-color: skyblue;
  }