CSS盒子居中的几种方法

学习笔记 CSS盒子居中的几种方法

<div class=boxA>
  <div class=boxB><div>
<div>

1:用flex布局实现盒子居中

.boxA {
          
   
  width: 200px;
  height: 200px;
  background-color: #000;
   /* 给父盒子添加flex布局 */
  display: flex;
 /* 主轴方向 垂直 从上往下 y轴 */
  flex-direction: column;
  /* 主轴居中 */
  justify-content: center;
  /* 侧轴居中 */
  align-items: center;
}
.boxB {
          
   
  width: 100px;
  height: 100px;
  background-color: red;
}

2:transfrom+margin

.boxA {
          
   
  width: 200px;
  height: 200px;
  background-color: #000;
  border: 1px solid #000;
}
.boxB {
          
   
  width: 100px;
  height: 100px;
  background-color: red;
  margin-left: 50%;
  margin-top: 50%;
  transform: translate(-50%, -50%);
}

3: transfrom + position(position:relative / absolute)

.boxA {
          
   
 	width: 200px;
    height: 200px;
    background-color:#000;
    /*(relative)给父级盒子设置相对定位 */
    position: relative;
}
.boxB{
          
   
 	width: 100px;
    height: 100px;
    background-color: red;
    /* (absolute)给子盒子设置绝对定位*/
    position: absolute;
    /* 向右、向下移动父盒子的一半 (偏移量) */
    left: 50%;
    top: 50%;
    /* translate若使用百分比,是相对于自身的比例的位移 */
    transform: translate(-50%, -50%);
}

4:position + margin负间距

.boxA {
          
   
    width: 200px;
    height: 200px;
    background-color:#000;
    /*(relative)给父级盒子设置相对定位 */
    position: relative;
}
.boxB {
          
   
	width: 100px;
    height: 100px;
    background-color: red;
    /* (absolute)给子盒子设置绝对定位*/
    position: absolute;
    top: 50%;
    left: 50%;
    /*margin负间距 */
    margin-left: -100px;
    margin-top: -100px;
}

5:table-cell

.boxA {
          
   
    display: table-cell;
    vertical-align: middle;
    width: 200px;
    height: 200px;
    border: 10px solid #000;
    background-color: #000;
}
.boxB {
          
   
    width: 100px;
    height: 100px;
    background-color:red;
    margin: 0 auto;
}
经验分享 程序员 微信小程序 职场和发展