1、相对定位
相对定位三大特性:1、不脱标(如果不设置方向上是属性) 2、形影分离 3、老家留坑,占着茅坑不拉屎。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .box1{ width: 100px; height: 100px; background-color: red; position: relative; top: 10px; left: 30px; } .box2{ width: 100px; height: 100px; background-color: green; } .box3{ width: 100px; height: 100px; background-color: blue; } </style> </head> <body> <div class="box1"> 1 </div> <div class="box2"> 2 </div> <div class="box3"> 3 </div> </body> </html>
相对定位用途:1、微调元素位置 2、父相子绝,做绝对定位的位置参考
2、绝对定位
绝对定位三大特性:1、脱标 2、提升层级 3、设置绝对定位后,行内元素也可以设置宽高。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> body{ width: 100%; height: 2000px; border: 10px solid green; } .box{ width: 200px; height: 200px; background-color: red; position: absolute; bottom: 100px; left: 18px; } </style> </head> <body> <div class="box"> </div> </body> </html>
2、父相子绝,子元素以父元素为参考点,此时父元素不一定是爸爸,也可能是爷爷,或者爷爷的爷爷。如果父盒子设置了相对定位,就以父盒子为参考点。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ padding: 0; margin: 0; } .father{ width:300px; height: 300px; position: relative; top:100px; left:50px; padding: 50px; background-color: yellow; } .son{ width: 100px; height: 100px; position: absolute; background-color: red; position: absolute; top:0px; left: 0; } </style> </head> <body> <div class="father"> <div class="son"> son </div> </div> </body> </html>
绝对定位居中方法,绝对定位脱标,margin:0 auto失效
left:50%;
margin-left:一半width;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .father{ width:100%; height: 40px; position: relative; background-color: #333 ; } .son{ width:1200px; height: 40px; background-color: red; position: absolute; left: 50%; margin-left: -600px; } </style> </head> <body> <div class="father"> <div class="son"></div> </div> </body> </html>
3、固定定位
特性:1.脱标 2.提升层级 3.固定不变 不会随页面滚动而滚动
作用: 1.返回顶部栏 2.固定导航栏 3.小广告
实现返回顶部
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ padding: 0; margin: 0; } .box{ width:1226px; height: 3000px; background: url(img/bobo.jpg); } .top{ width: 50px; height: 50px; background-color: #808080; text-align: center; line-height: 50px; position: fixed; bottom: 30px; right: 10px; } a{ text-decoration: none; font-size: 40px; color: white; } a:hover{ cursor: pointer; } </style> </head> <body> <div class="box"> <div class="top" style="display: none;"> <a class="ss"> ^ </a> </div> </div> </body> <script src="jquery-3.2.1.js"></script> <script type="text/javascript"> $(function(){ $('.top').click(function(){ $('html').animate({'scrollTop':0},1000); }) $(window).scroll(function(){ if($(window).scrollTop() == 0){ $('.top').hide(); }else{ $('.top').show(); } console.log($(window).scrollTop()); }) }) </script> </html>