<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> #test1{ width:400px; height:400px; background:green; } p{ margin:0px; padding:0px; } #p1{ width:100px; height:100px; background:red; } #p2{ width:100px; height:100px; background:orange; } </style> </head> <body> <div id="test1"> <p id="p1">相对定位是指元素在其正常的位置,偏移某些像素</p> <p id="p2">相对定位是指元素在其正常的位置,偏移某些像素</p> </div> </body> </html>
未添加相对定位偏移属性:html
添加属性后:ide
#p1{ width:100px; height:100px; background:red; position:relative; top:20px; left:20px; }
若是要改变偏移方向只需直接更改偏移的方向便可,如:3d
#p1{ width:100px; height:100px; background:red; position:relative; /*top:20px; left:20px;*/ right:20px; bottom:20px; }
绝对定位:htm
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> #test1{ width:400px; height:400px; background:green; } p{ margin:0px; padding:0px; } #p1{ width:100px; height:100px; background:red; position:relative; /*top:20px; left:20px;*/ right:20px; bottom:20px; } #p2{ width:100px; height:100px; background:orange; } #test2{ width:400px; height:400px; background:blue; } #p3{ width:100px; height:100px; background:gray; } </style> </head> <body> <div id="test1"> <p id="p1">相对定位是指元素在其正常的位置,偏移某些像素</p> <p id="p2">相对定位是指元素在其正常的位置,偏移某些像素</p> </div> <div id="test2"> <p id="p3">绝对定位相对于父元素的top,left,right,bottom来定位</p> </div> </body> </html>
未写入绝对定位属性的效果:blog
写入绝对定位:utf-8
#p3{ width:100px; height:100px; background:gray; position:absolute; top:20px; left:30px; }
上面的效果为何是这样的呢,由于用绝对定位时父元素要求有position属性才行,不然将依据父的父....一直到body, 哪一个祖先有position属性,相对哪一个祖先,若是都没有则相对于body。那么咱们就为代码中的p3父元素设置一个position属性:it
#p3{ width:100px; height:100px; background:gray; position:absolute; top:20px; left:30px; }
若是再添加一块的话会是什么效果呢:io
#p4{ width:100px; height:100px; background:pink; position:absolute; top:30px; left:40px; } </style> </head> <body> <p id="p4"></p> </div> </body> </html>
新增的粉红块漂浮在了灰块上方,那么要是想让灰块漂浮在粉块上方呢,能够用到一个属性z-index:取的值越大,哪块就会在上方效果以下:class
#p3{ width:100px; height:100px; background:gray; position:absolute; top:20px; left:30px; z-index:10000; }