绝对定位的盒子水平/垂直居中的三种方式

144 阅读1分钟
  • 绝对定位的盒子水平/垂直居中

  • 第1种
.box{ 
    position: absolute; 
    top: 0; 
    right: 0; 
    bottom: 0; 
    left: 0; 
    margin:auto; 
 }
  • 第2种
.box{ 
    position: absolute; 
    top: 50%; 
    margin-top: -300px ; /*取值为元素负值自身高度的一半*/ 
    left: 50%; 
    margin-left: -200px; /*取值为元素负值自身宽度的一半*/ 
    width: 400px; 
    height: 600px; 
 }
  • 注意:这两种方式的前提条件是必须有自身的宽度和高度。
  • 第3种
.box { 
    position:absolute; 
    top:50%; 
    left:50%; 
    transform:translate(-50%,-50%); 
 }