04.绝对定位元素的布局.html 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. .box1{
  10. width: 500px;
  11. height: 500px;
  12. background-color: #bfa;
  13. position: relative;
  14. }
  15. .box2{
  16. width: 100px;
  17. height: 100px;
  18. background-color: orange;
  19. position: absolute;
  20. margin-left: auto;
  21. margin-right: auto;
  22. left: 0;
  23. right: 0;
  24. margin-top: auto;
  25. margin-bottom: auto;
  26. top: 0;
  27. bottom: 0;
  28. }
  29. /*
  30. 水平布局
  31. left + margin-left + border-left + padding-left + width + padding-right + border-right + margin-righ + right = 包含块的内容区的宽度
  32. -当我们开启了绝对定位后:水平方向的布局等式就需要添加left和right两个值
  33. 此时规则和之前一样,只是多添加了两个值:
  34. 当发生过度约束时:
  35. 如果9个值中没有auto,则自动调整right值以使等式满足
  36. 如果有auto,则自动调整auto的值以使等式满足
  37. -可设置auto的值
  38. margin、width、left、right
  39. -因为left和right的默认值是auto,所以如果不指定left和right,
  40. 则等式不满足时,会自动调整这两个值
  41. 垂直方向布局的等式也必须满足:
  42. top + margin-top/bottom + padding-top/bottom + border-top/bottom+height = 包含块的高度
  43. */
  44. </style>
  45. </head>
  46. <body>
  47. <div class="box1">
  48. <div class="box2"></div>
  49. </div>
  50. </body>
  51. </html>