这里的demo我只是举一下absolute的例子,由于fixed和relative都比较好理解,就没必要多说。css
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> <style type="text/css"> div{border:2px red solid;} body{background-color: #999;} #box1{ width: 400px; height: 400px; padding: 20px; background-color: #444; margin-left: 100px; margin-top: 100px; } #box2{ width: 300px; height: 300px; background-color: #777; position: absolute; } </style> </head> <body> <div id="box1"> <div id="box2"> </div> </div> </body> </html>
效果
html
这个就是未设置TRBL时效果。接着咱们设置一下TBRL来看看,更改一下代码浏览器
#box2{ width: 300px; height: 300px; background-color: #777; position: absolute; top:50px; left:50px; }
效果:
布局
这个box2就是相对于根元素来定位的。由于它的祖辈容器中没有一个设置了postion的。接着咱们在box1中添加position: relative;post
#box1{ width: 400px; height: 400px; padding: 20px; background-color: #444; margin-left: 100px; margin-top: 100px; position: relative; }
效果:
以上三种状况就简明解释了absolute的一些特性。优化
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> <style type="text/css"> div{border:2px red solid;} body{background-color: #999;} #box1{ width: 400px; height: 400px; padding: 20px; background-color: #444; margin-left: 100px; margin-top: 100px; position: relative; } #box2{ width: 300px; height: 300px; background-color: #777; position: absolute; top:50px; left:50px; } </style> </head> <body> <div id="box1"> <div id="box2"> </div> <p>这是一段文字,若是看不见我就说明我被遮住了,或者被遮住一部分。</p> </div> </body> </html>