-
-
第一种方式已知宽高:
div{ width: 200px; height: 200px; position: absolute; top: 50%; left: 50%; margin-left: -100px; margin-right: -100px; background: #f00; 元素宽度高度都是200px,加相对定位,记得父相子绝,给盒子绝对定位的时候都是top,left都50%,元素靠下靠右了 所以要用marign负值拽回来,元素宽度和高度的一半 }
第二种方式未知宽高:
div{ width: 200px; height: 200px; position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto; background: #f00; 元素宽度高度都是200px,加相对定位,记得父相子绝,给盒子绝对定位的时候都是top,left,bottom,right全是0,盒子就居中了 }
-
**第三种方式未知宽高:**
```css
div{
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #000;
元素宽度高度都是200px,加相对定位,记得父相子绝,给盒子绝对定位的时候都是top,left都50%,元素靠下靠右了
所以要用C3的transform:translate(-50%, -50%)负值拽回来,元素宽度和高度的一半
}