目录
relative 相对定位
absolute 绝对定位
fixed 固定定位
sticky 粘性定位
position:relative 、absolute、fixed 、sticky (四选一)
top:距离上面的像素
bottom:距离底部的像素
left:距离左边的像素
right:距离右边的像素
relative 相对定位
相对于自身在原来默认的位置,进行 top、bottom、left、right 来调整位置
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
 <style>
/*    相同的样式可以写一起,不要重复操作*/
#div_1,#div_2 { 
    width: 20px;
    height: 20px;
    border: 1px solid ;
    color: white;
    font-size: 5px;
 }
 #div_1{
    background: black;
 }
  #div_2{
    position: relative;
    left: 20px;
    top:30px;
    background: red;
 }
</style>
</head>
<body>
<div id="div_1">我是一个黑框框</div>
<div id="div_2"> 我是一个红框框</div>
</body>
</html>

absolute 绝对定位
没有已定位的祖先元素,absolute 相对于浏览器页面 进行定位
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
 <style>
/*    相同的样式可以写一起,不要重复操作*/
#div_1,#div_2 { 
    width: 20px;
    height: 20px;
    border: 1px solid ;
    color: white;
    font-size: 5px;
 }
 #div_1{
    background: black;
 }
  #div_2{
    position: absolute;
    left: 20px;
    top:0px;
    background: red;
 }
</style>
</head>
<body>
<div id="div_1">我是一个黑框框</div>
<div id="div_2"> 我是一个红框框</div>
</body>
</html> 
定位祖先元素进行定位。div_1 已经做 position: absolute,且是 div_1 包含了 div_2 ,所以 div_1就是已经定位的祖先元素
<style>
#div_1{
    position: absolute;
    top:10px;
    background: black;
 }
  #div_2{
    position: absolute;
    left: 20px;
    top:10px;
    background: red;
 }
</style>
</head>
<body>
<div id="div_1"> 
    <div id="div_2"> 我是一个红框框</div>
</div>
fixed 固定定位
fixed 是相对于浏览器窗口进行定位的。无论页面如何滚动,页面都不会挪动位置
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
 	<title></title>
	<style>
 .nav {
    width: 100%;
    height: 25 px;
    background-color: blue;
    color: white;
    position: fixed;
    top: 0;
    left: 0;    
  }
</style>
</head>
<body>
<div class="nav">我动不了了导航栏</div>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
</body>
</html>
sticky 粘性定位
元素刚开始就按文档正常一样显示,但是当页面滚动到指定位置的时候,它就会固定住。
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
 	<title></title>
	<style>
 .nav {
    width: 100%;
    height: 25 px;
    background-color: blue;
    color: white;
    position: sticky;
    top: 50px;
   }
</style>
</head>
<body>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<div class="nav">我是导航栏</div>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
<p>页面内容。。。。。。</p>
</body>
</html>
当页面下拉的时候,就会停留在离顶部 50 像素的位置




















