18_定位.html 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. .box{
  9. width: 400px;
  10. height: 400px;
  11. border: 3px solid black;
  12. /* 设置为相对定位 相对于自己的位置*/
  13. position: relative;
  14. top:100px;
  15. left:200px;
  16. }
  17. .div1{
  18. width: 100px;
  19. height: 100px;
  20. background-color: red;
  21. /* 绝对定位的元素的位置相对于最近的已定位祖先元素 如果元素没有已定位的父元素,那么它的位置相对于<html>*/
  22. position: absolute; /* 设置为绝对定位 */
  23. /* right: 0;
  24. bottom: 0; */
  25. /* top: 100px;
  26. left: 50px; */
  27. top:50%;
  28. left:50%;
  29. margin-top:-50px;
  30. margin-left: -50px;
  31. z-index: 1; /* 设置层级 数字越大越在上面 */
  32. }
  33. /* 固定定位的元素的位置相对于浏览器窗口 */
  34. .div2{
  35. position: fixed;
  36. right: 50px;
  37. bottom: 50px;
  38. }
  39. .div3{
  40. width: 100px;
  41. height: 100px;
  42. background-color: blue;
  43. position: absolute;
  44. top: 200px;
  45. left: 200px;
  46. z-index: 2; /* 设置层级 数字越大越在上面 */
  47. }
  48. </style>
  49. </head>
  50. <body>
  51. <div class="box">
  52. <div class="div1"></div>
  53. <div class="div3"></div>
  54. </div>
  55. <div class="div2">返回顶部</div>
  56. </body>
  57. </html>