div居中

 <div class="parentDiv">
      <div class="childDiv"></div>
    </div>
.parentDiv {
    width:400px;
    height: 100px;
    background-color: #00ff00;
    margin: 20px;
  }
  
  .childDiv {
      width: 200px;
      height:50px;
      background-color: #ff0000;
  }

方法一:margin:0 auto

.childDiv{
    margin:0 auto;
  }

效果:

方法二:如果给子盒子div.childDiv设置display: inline-block不影响整体布局时,可以将子盒子转化为inline-block,对父盒子设置text-align:center实现居中对齐。CSS代码如下:

 .parentDiv {
    text-align: center;
}

  .parentDiv .childDiv {
      display: inline-block;
  }

方法三(实现了水平垂直居中):将父盒子设置为table-cell元素,可以使用text-align: center;和vertical-align: middle;实现水平、垂直居中。比较好的解决方案是利用三层结构模拟父子结构。这里写两层的:

.parentDiv{
  display: table-cell;
    text-align: center;
    vertical-align: middle;
}

.childDiv {
    display: inline-block;
}

方法四:绝对定位居中(利用margin实现偏移)

.parentDiv {
    position: relative;
}

.parentDiv .childDiv {
    position: absolute;
    left:50%;
    top:50%;
    margin-left:-100px; /*利用margin实现偏移,设置为宽度和高度的一半的负值
    margin-top:-25px;  
    
}

方法五:绝对定位居中(利用transform实现偏移)

.parentDiv {
    position: relative;
}

.parentDiv .childDiv {
    position: absolute;
    left:50%;
    top:50%;
    transform: translate(-50%,-50%);
}

方法六:绝对定位居中(利用margin:auto实现偏移)

  同样对子盒子实现绝对定位,这里使用top、right、bottom、left均为0,margin为auto实现偏移

/*绝对定位实现居中,margin:auto实现偏移*/
.parentDiv {
    position: relative;
}

.parentDiv .childDiv {
    position: absolute;
    left:0; /*top、right、bottom、left均为0*/
    top:0;
    right: 0;
    bottom: 0;
    margin: auto;
}

方法七:使用弹性盒模型(flexbox)实现居中。

.parentDiv {
    display: -webkit-box; /*Safari*/
    display: -moz-box; /*Firefox*/
    display: -ms-flexbox; /*IE*/
    display: -webkit-flex; /*Chrome*/
    display: flex; 
    -webkit-box-align: center;
    -moz-box-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
    -webkit-box-pack: center;
    -moz-box-pack: center;
    -ms-flex-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
}

猜你喜欢

转载自www.cnblogs.com/ceceliahappycoding/p/10544652.html