1. <p>当需要一个元素不以文档流规则定位的时候,应该使用position这个属性</p>
  2. <ul>
  3. <li>static是position的默认属性值</li>
  4. <li>relative是相对自身定位</li>
  5. <li>absolute是相对第一个position的非static的祖先定位</li>
  6. <li>fixed是相对浏览器窗口定位</li>
  7. <li>stick粘性定位</li>
  8. </ul>
  9. <p>要实现定位,除了设置定位参照元素之外,还需要top,right,bottom,left来具体描述定位</p>

relative - 相对自身

  1. <style>
  2. .d2{
  3. position: relative;
  4. top: 10px;
  5. left: 20px;
  6. height: 50px;
  7. width: 50px;
  8. border: 1px solid black;
  9. }
  10. </style>
  11. <body>
  12. <p>当需要一个元素不以文档流规则定位的时候,应该使用position这个属性</p>
  13. <ul>
  14. <li>static是position的默认属性值</li>
  15. <li>relative是相对自身定位</li>
  16. <li>absolute是相对第一个position的非static的祖先定位</li>
  17. <li>fixed是相对浏览器窗口定位</li>
  18. <li>stick粘性定位</li>
  19. </ul>
  20. <p>要实现定位,除了设置定位参照元素之外,还需要top,right,bottom,left来具体描述定位</p>
  21. <div id="parent">
  22. <div class="d1">
  23. <div class="d2">如果一个元素使用relative定位,相对自身原来的位置定位,对文档流没有影响</div>
  24. <div class="d3">d3</div>
  25. </div>
  26. <button>按钮1</button>
  27. <button>按钮2</button>
  28. </div>
  29. </body>

absolute - 相对父元素

  1. <style>
  2. .d1{
  3. position: relative;
  4. height: 300px;
  5. width: 300px;
  6. border: black 1px solid;
  7. }
  8. .d2{
  9. position: relative;
  10. height: 100px;
  11. width: 100px;
  12. border: red 1px solid;
  13. }
  14. .d3{
  15. position: absolute;
  16. right: 0;
  17. bottom: 0;
  18. height: 50px;
  19. width: 50px;
  20. border: green 1px solid;
  21. }
  22. </style>
  23. <body>
  24. <p>如果一个元素如果需要相对他的非static的祖先元素定位,设置position为absolute</p>
  25. <div class="d1">
  26. <div class="d2">
  27. <div class="d3"></div>
  28. </div>
  29. </div>
  30. </body>

fixed - 相对窗口

  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>fixed</title>
  7. <style>
  8. /* 块级元素的position如果为absolute或是fixed的时候,默认宽为0 */
  9. .d1{
  10. position:fixed;
  11. }
  12. .s1{
  13. position: absolute;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <div class="d1"></div>
  19. <span class="s1"></span>
  20. </body>
  21. </html>

z-index - 层级

  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. .d1{
  9. position: absolute;
  10. z-index: 6;
  11. opacity: .5; /*透明度*/
  12. width: 300px;
  13. height: 300px;
  14. background-color: pink;
  15. }
  16. .d2{
  17. position: absolute;
  18. z-index: 3;
  19. width: 200px;
  20. height: 200px;
  21. background-color: salmon;
  22. }
  23. .d3{
  24. position: absolute;
  25. z-index: 6;
  26. width: 100px;
  27. height: 100px;
  28. background-color: brown;
  29. }
  30. </style>
  31. </head>
  32. <body>
  33. <p>如果一个元素脱离了文档,那么他和其他文档流元素就不在一个平面上</p>
  34. <div class="d1"></div>
  35. <div class="d2"></div>
  36. <div class="d3"></div>
  37. </body>
  38. </html>