image.png

position:absolute;

元素会被移出正常文档流,并不为元素预留空间,通过指定元素相对于最近的非 static 定位祖先元素的偏移,来确定元素位置。绝对定位的元素可以设置外边距(margins),且不会与其他边距合并。

第一种方式:absolute + 负margin

  1. .father {
  2. position: relative;
  3. }
  4. .child{
  5. width: 100px;
  6. height: 100px;
  7. position: absolute;;
  8. top: 50%;
  9. left: 50%;
  10. margin-left: -50px;
  11. margin-top: -50px;
  12. }

分析:暂不设置margin-left: -50px; margin-top: -50px;

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>垂直居中</title>
  6. <style>
  7. * {
  8. padding: 0;
  9. margin: 0;
  10. }
  11. .body {
  12. width: 300px;
  13. height:300px;
  14. position: relative;
  15. background-color:rosybrown;
  16. }
  17. .box {
  18. width: 100px;
  19. height: 100px;
  20. position: absolute;
  21. top: 50%;
  22. left: 50%;
  23. background-color: beige;
  24. }
  25. </style>
  26. </head>
  27. <body>
  28. <div class="body">
  29. <div class="box">
  30. 绝对定位元素
  31. </div>
  32. </div>
  33. </body>
  34. </html>

得到:
image.png
为什么要取子元素宽度的一半?
绝对定位的百分比是相对于父元素的宽高,绝对定位是基于子元素的左上角居中,但期望子元素的中心居中显示,如图,可以借助外边距的负值,负的外边距可以让元素向相反方向定位,通过指定子元素的外边距为子元素宽度一半的负值,就可以让子元素居中了

第二种方式:absolute + margin auto

margin:用来计算元素对应方向应该获得的剩余空间大小

  1. .father {
  2. position: relative;
  3. }
  4. .child{
  5. width: 100px;
  6. height: 100px;
  7. position: absolute;;
  8. top: 0;
  9. left: 0;
  10. right: 0;
  11. bottom: 0;
  12. margin: auto;
  13. }

image.png

第三种方式:absolute + calc

image.png
减去子元素宽度的一半