绝对定位结合margin:auto.html 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>绝对定位结合margin: auto</title>
  7. <style>
  8. #box {
  9. width: 300px;
  10. height: 300px;
  11. background: #ddd;
  12. position: relative;
  13. }
  14. #child {
  15. width: 200px;
  16. height: 100px;
  17. background: orange;
  18. position: absolute;
  19. top: 0;
  20. bottom: 0;
  21. margin: auto;
  22. line-height: 100px;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <h1>绝对定位结合margin: auto</h1>
  28. <p>
  29. 这种实现方式的两个核心是:把要垂直居中的元素相对于父元素绝对定位,top和bottom设为相等的值,我这里设成了0,当然也可以设为 99999px 或者 -99999px 无论什么,只要两者相等就行,这一步做完之后再将要居中元素的 margin 属性值设为 auto,这样便可以实现垂直居中了。
  30. 被居中元素的宽高也可以不设置,但不设置的话就必须是图片这种自身就包含尺寸的元素,否则无法实现。
  31. </p>
  32. <div id="box">
  33. <div id="child">test vertical align</div>
  34. </div>
  35. </body>
  36. </html>