position的默认值是static,(也就是说对于任意一个元素,如果没有定义它的position属性,那么它的position:static)
如果你想让这个#demo里的一个div#sub相对于#demo定位在右上角的某个地方,应该给#demo相对定位,#sub绝对定位。
absolute是相对于自己最近的父元素来定位的,如果你不给#demo相对定位,那么#sub的绝对定位就是相对于body来定位的。
relative是相对于自己来定位的,例如:#demo{position:relative;top:-50px;},这时#demo会在相对于它原来的位置上移50px。
另:relative 不脱离文档流,absolute 脱离文档流。也就是说:relative 的元素尽管表面上看到它偏离了原来的位置,但它实际上在文档流中还是没变。absolute的元素不仅位置改变了,同时也脱离了文档流。
1.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 2. 3.<html xmlns="http://www.w3.org/1999/xhtml"> 4.<head> 5.<meta http-equiv="content-type" content="text/html; charset=utf-8"> 6.<title>position</title> 7.<style type="text/css"> 8. <!-- 9. body{ 10. font-size:12px; 11. margin:0 auto; 12. } 13. 14. div#demo{ 15. position:relative; 16. border:1px solid #000; 17. margin:50px; 18. top:-50px; 19. line-height:18px; 20. overflow:hidden; 21. clear:both; 22. height:1%; 23. } 24. 25. div#sub{ 26. position:absolute; 27. right:10px; 28. top:10px; 29. } 30. 31. div.relative{ 32. position:relative; 33. left:400px; 34. top:-20px; 35. } 36. 37. div.static,div.fixed,div.absolute,div.relative{ 38. width:300px; 39. } 40. 41. div.static{ 42. background-color:#bbb; 43. position:static; 44. } 45. 46. div.fixed{ 47. background-color:#ffc0cb; 48. } 49. 50. div.absolute{ 51. background-color:#b0c4de; 52. } 53. 54. div.relative{ 55. background-color:#ffe4e1; 56. } 57. --> 58.</style> 59.</head> 60.<body> 61. <div id="demo"> 62. <div class="static">static: 默认值。无特殊定位,对象遵循HTML定位规则 </div> 63. <div id="sub" class="absolute">absolute: 将对象从文档流中拖出,使用left,right,top,bottom 等属性相对于其最接近的一个最有定位设置的父对象进行绝对定位。如果不存在这样的父对象,则依据body对象。而其层叠通过z-index属性定义 </div> 64. <div class="fixed">fixed:未支持。对象定位遵从绝对(absolute)方式。但是要遵守一些规范 </div> 65. <div class="relative">relative:对象不可层叠,但将依据 left,right,top,bottom 等属性在正常文档流中偏移位置 </div> 66. </div> 67.</body> 68.</html>