天天看點

定位元素position的使用

定位元素position的使用

定位元素position的作用:手動控制元素在包含塊中的精确位置。

1、position:static(預設值)

2、position:relative 相對定位

相對于自身的定位,不脫離文檔流(即元素發生定位時還會保留原始的位置),一般用于元素的微調。

<!DOCTYPE html><html ><head>    
<meta charset="UTF-8">    
<meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title>    
<style>      
*{          
padding: 0px;          
margin: 0px;      
}      
.box{          
background-color: aqua;          
width: 1200px;          
height: 200px;          
float: left;      
}      
.box1{          
width: 400px;          
height: 100px;          
background-color: blanchedalmond;          
float: left;      
}      
.box2{          
width: 400px;         
height: 100px;          
background-color: green;          
float: left;          
position: relative;          
left: 20px;      
}      
.box3{          
width: 400px;          
height: 100px;         
background-color: blue;          
float: left;      
}    
</style>
</head>
<body>  
<div class="box">      
<div class="box1"></div>      
<div class="box2"></div>      
<div class="box3"></div>

</div>
</body>
</html>
           

相對定位會改變相鄰盒子的位置。

定位元素position的使用

3、position:absolute 絕對定位

相對于父級元素或祖先元素的定位,脫離文檔流,相對定位一般都是配合絕對定位元素使用;

<!DOCTYPE html><html lang="en"><head>    
<meta charset="UTF-8">    
<meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title>    
<style>      
*{          
padding: 0px;          
margin: 0px;      
}      
.box{          
background-color: aqua;          
width: 1200px;          
height: 200px;          
position: relative;      
}      
.box1{         
 width: 400px;          
 height: 100px;          
 background-color: blanchedalmond;          
 float: left;      
 }      
 .box2{          
 width: 400px;          
 height: 100px;          
 background-color: green;          
 float: left;          
 position: absolute;          
 left: 30px;          
 bottom: 30px;      
 }      
 .box3{          
width: 400px;         
height: 100px;         
background-color: blue;         
float: left;      
   }      
.clearfix::after{          
clear: both;          
content: "";          
display: block;      
}    
</style>
</head>
<body>  
<div class="box clearfix">      
<div class="box1"></div>      
<div class="box2"></div>      
<div class="box3"></div>
  </div>
  </body>
  </html>
           
定位元素position的使用

4、position:fixed(固定定位)

脫離文檔流,當使用固定定位時元素自動成為塊元素,可以改變寬度高度,一般用于固定導覽列、邊欄導覽列等。