练习9_元素居中.html 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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>Document</title>
  7. <style>
  8. .box1{
  9. width: 400px;
  10. height: 400px;
  11. border:3px dashed red;
  12. position: relative;
  13. }
  14. /* 父元素 子元素 大小都确定的情况下 */
  15. .box2{
  16. width: 200px;
  17. height: 200px;
  18. background-color: blue;
  19. position: relative;
  20. top:100px;
  21. left: 100px;
  22. }
  23. /* 父元素未知大小 子元素大小已知 */
  24. .box3{
  25. width: 200px;
  26. height: 200px;
  27. background-color: green;
  28. position: absolute;
  29. top:50%;
  30. left: 50%;
  31. margin-top: -100px;
  32. margin-left: -100px;
  33. }
  34. </style>
  35. </head>
  36. <body>
  37. <div class="box1">
  38. <div class="box2"></div>
  39. </div>
  40. <div class="box1">
  41. <div class="box3"></div>
  42. </div>
  43. </body>
  44. </html>