一共分为5中, static , relative, absolute, fixed, inherit, 默认是static,
relative, 相对定位,针对父元素相对定位
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>相对定位</title> <style> .rel { 100px; height: 100px; position: relative; background-color: blue; left: 100px; } .rel2 { 100px; height: 100px; position: relative; background-color: red; top: -50px; left: 100px; } </style> </head> <body> <div class="rel"> </div> <div class="rel2"></div> <div></div> </body> </html>
absolute 绝对定位, 相对窗口的左上角的位置,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>绝对定位</title> <style> .pos { 300px; height: 300px; /*position: absolute;*/ background: blue; } .pos2 { 100px; height: 100px; position: absolute; background: red; /*left: 200px;*/ right: 100px; } body{ height: 3000px; } </style> </head> <body> <div class="pos"> <div class="pos2"></div> </div> </body> </html>
fixed 固定定位,不管浏览器器多高,都固定在窗口中的固定位置
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>固定定位</title> <style> .fix{ 100%; height: 100px; position: fixed; background: blue; left: 0px; bottom: 0px; } body{ height: 3000px; } </style> <style> .bro{ 300px; height: 300px; background: black; position: absolute; left: 300px; top: 0px; } .test{ 100px; height: 100px; background: yellow; position: fixed; left: 100px; top: 100px; } </style> </head> <body> <div class="fix"></div> <div class="bro"> <div class="test"></div> </div> </body> </html>
inherit 继承父元素的position位置
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>固定定位</title> <style> .fix{ 100%; height: 100px; position: fixed; background: blue; left: 0px; bottom: 0px; } body{ height: 3000px; } </style> <style> .bro{ 300px; height: 300px; background: black; position: absolute; left: 300px; top: 0px; } .test{ 100px; height: 100px; background: yellow; position: fixed; left: 100px; top: 100px; } </style> </head> <body> <div class="fix"></div> <div class="bro"> <div class="test"></div> </div> </body> </html>
联系一个居中的登录布局
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login Center</title> <style> .login { 200px; height: 200px; left: 50%; top: 50%; position: fixed; margin-top: -100px; margin-left: -100px; background: blue; } .login .title{ position: relative; 100%; height: 15px; padding: 5px 0px 5px 0px; top: 0px; background: yellow; z-index: -1; } .login .close{ 10px; height: auto; background: red; postion: relative; margin-top: -20px; margin-left: 190px; z-index: 3; cursor: pointer; } </style> <script type="text/javascript"> function closeXXX() { alert("i am close") } function titleXXX() { alert("i am title") } </script> </head> <body> <div class="login"> <div class="title" onclick="titleXXX()"> i am title </div> <div class="close" onclick="closeXXX()">X</div> </div> </body> </html>