25_定位.html 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. .box2{
  15. width: 200px;
  16. height: 200px;
  17. background-color: blue;
  18. /* margin-top: 50px; */
  19. /* 相对定位 元素相对于其原来的位置进行定位 */
  20. /* 定位之后 可以使用四个方向属性 top bottom left right */
  21. position: relative;
  22. top:50px;
  23. }
  24. .box3{
  25. width: 100px;
  26. height: 100px;
  27. background-color: green;
  28. }
  29. span{
  30. background-color: yellow;
  31. /* 绝对定位 元素相对于其最近的定位祖先元素进行定位 */
  32. /* 满足两个条件 1 必须是祖先元素 2这个祖先元素必须定位(不能使用static) */
  33. position: absolute;
  34. /* right: 0;
  35. bottom: 0; */
  36. /* 50% 表示距离顶部50% 相较于父元素的高度 */
  37. top: 50%;
  38. /* 50% 表示距离左侧50% 相较于父元素的宽度 */
  39. left: 50%;
  40. /* margin 使用负数的时候 可以将元素向相反方向移动 */
  41. margin-top: -20px;
  42. }
  43. </style>
  44. </head>
  45. <body>
  46. <div class="box1">
  47. <div class="box2"></div>
  48. <div class="box3"></div>
  49. <span>这是一个span标签</span>
  50. </div>
  51. </body>
  52. </html>