定位的作用:
在css中定位一般用于将块级元素移动到一个地方,使其脱离原本的固定位置(自由移动该元素或固定在屏幕的一个位置)。
定位的用法:
通过 position 属性来设置元素的定位模式,position有四个常用值分别是: fixed(固定定位)、absolute(绝对定位)、relative(相对定位)、static(静态定位及默认定位)。
在通过偏移量来确定元素的位置,偏移量常用的属性有4个:
left:元素向右偏移
right:元素向左偏移
top:元素向下偏移
bottom:元素向上偏移
注意事项:
1.相对定位不会改变元素样式,只改变元素所处的空间,元素依旧会独占一行。
绝对定位会更改元素样式,使元素类似于行内块级元素。
固定定位不会占据原本的位置,会使元素脱离标准流,改变元素性质。
2.如果不设置偏移量元素位置不会改变
3.如果元素之前未设置定位,则默认以body为定位点,如果元素之前设置过定位则以向上查找到的最近的元素为定位点,同时前一个元素的定位尽量为相对定位。(子绝父相)
使用方式及案例:
固定定位:
position:fixed;
案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- css样式表 -->
<style>
.box {
height: 500px;
width: 100px;
background-color: red;
position: fixed;
<!-- 设置偏移量-->
right: 0;
top: 200px;
}
</style>
</head>
<body>
<!-- 固定定位 -->
<h1>这是顶部</h1>
<br>*100
<h1>这是底部</h1>
<div class="box"></div>
</body>
</html>
绝对定位:
position:absolute
案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- css样式表 -->
<style>
.big {
width: 500px;
height: 500px;
background-color: red;
margin: auto;
}
.little {
width: 200px;
height: 200px;
background-color: blue;
/* 绝对定位 */
position:absolute;
/* 垂直水平居中 */
top: 50%;
margin-top: -100px;
left: 50%;
margin-left: -100px;
}
</style>
</head>
<body>
<!-- 绝对定位 -->
<div class="big">
<div class="little"></div>
</div>
</body>
</html>
相对定位:
positon:relative;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- css样式表 -->
<style>
.box{
height: 100px;
width: 1000px;
background-color: red;
position: relative;
left: 100px;
}
</style>
</head>
<body>
<!-- 相对定位 -->
<div class="box">这是相对定位</div>
</body>
</html>
静态定位:
position:static;
静态定位是每个元素的默认定位方式及默认的文档流定位。通常用于清除定位。