绝对定位和负外边距进行垂直居中.html 931 B

123456789101112131415161718192021222324252627282930313233343536
  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>使用绝对定位和负外边距进行垂直居中</title>
  7. <style>
  8. #box {
  9. width: 300px;
  10. height: 300px;
  11. background: #ddd;
  12. position: relative;
  13. }
  14. #child {
  15. width: 50%;
  16. height: 30%;
  17. background: orange;
  18. position: absolute;
  19. top: 50%;
  20. margin: -15% 0 0 0;
  21. }
  22. </style>
  23. </head>
  24. <body>
  25. <h1>使用绝对定位和负外边距进行垂直居中</h1>
  26. <p>这种方式的原理实质上和前两种相同。补充的一点是:margin 的取值也可以是百分比,这时这个值规定了该元素基于父元素尺寸的百分比,可以根据实际的使用场景来决定是用具体的数值还是用百分比。</p>
  27. <div id="box">
  28. <div id="child">test vertical align</div>
  29. </div>
  30. </body>
  31. </html>