《1》
当我们要使用绝对定位的时候,必须要有两个条件
1》必须给父元素加定位属性,一般建议使用 position:relative(即:给父元素设为相对定位);
2》给子元素,加绝对定位position:absolute(给子元素设置为绝对定位); 同时加方向属性(top ,left,rigth,bottom)
绝对定位是以父元素为基准点,进行定位(如果他没有父元素,或者它的父元素没有设置position:relative属性)它就会以<body>为基准点进行定位。绝对定位会脱离文档流(即:他浮动起来了,不再占据原来的位置了)
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> body { margin:0px; padding:0px; } div { width: 100px; height: 100px; } #main { width:500px; height:500px; border:1px solid red; margin:0px 250px; } #a { background-color: red; } #b { background-color: green; top:100px; left:100px } #c { background-color: blue; height:150px; width:150px; } </style> </head> <body> <div id="main"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body> </html>
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> body { margin:0px; padding:0px; } div { width: 100px; height: 100px; } #main { width:500px; height:500px; border:1px solid red; margin:0px 250px; /*position:relative;*/ /*不给父元素设置相对定位,那么子元素就会以body为基准进行定位*/ } #a { background-color: red; } #b { background-color: green; top: 100px; left: 100px ; position:absolute; /*给B设置绝对定位*/ } #c { background-color: blue; height:150px; width:150px; } </style> </head> <body> <div id="main"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body> </html>
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> body { margin:0px; padding:0px; } div { width: 100px; height: 100px; } #main { width:500px; height:500px; border:1px solid red; margin:0px 250px; position:relative; /*给父元素设置相对定位,那么子元素进行绝对定位的时候就会以父元素为基准进行定位*/ } #a { background-color: red; } #b { background-color: green; top: 100px; left: 100px ; position:absolute; /*给B设置绝对定位*/ } #c { background-color: blue; height:150px; width:150px; } </style> </head> <body> <div id="main"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body> </html>
绝对定位 position:absolute,相对定位 position:relative
原文:http://blog.csdn.net/fanbin168/article/details/44986585