css绝对定位元素的居中

134 阅读1分钟
  1. 使用 负margin
.div1 {
  border:1px solid red;
  width:100px;
  height:200px;
  position:absolute;
  top:50%;
  left: 50%;
  margin-top: -100px;     //向上移动盒子高度的一半      
  margin-left: -50px;     //向左移动盒子宽度的一半 
}
  1. 使用 translate
  • translate 允许元素单独声明平移变换,并独立于 transform 属性
.div1 {
  border:1px solid red;
  width:100px;
  height:200px;
  position:absolute;
  top:50%;
  left:50%;
  transform: translate(-50%,-50%);      //以百分号为单位表示平移的长度是相对于自身而言的
}