定位可以将一个盒子固定在一个位置。
使用方法: 选择器 {
position:属性值;
}
属性值:
static 静态定位(默认值)
relative 相对定位
absolute 绝对定位
fixed 固定 定位
相对定位 position: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>
<style>
.box {
width: 500px;
height: 500px;
background-color: blue;
margin-left: 100px;
}
.box1 {
width: 200px;
height: 200px;
background-color: pink;
position: relative;
left: 100px;
}
.box2 {
width: 100px;
height: 100px;
background-color: gold;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
</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>
<style>
.box {
width: 500px;
height: 500px;
background-color: blue;
margin-left: 100px;
}
.box1 {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
left: 100px;
}
.box2 {
width: 100px;
height: 100px;
background-color: gold;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>
<!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>
<style>
.box {
width: 500px;
height: 500px;
background-color: blue;
margin-left: 100px;
position: relative;
}
.box1 {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
left: 100px;
}
.box2 {
width: 100px;
height: 100px;
background-color: gold;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>
固定定位 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>
<style>
.box {
width: 500px;
height: 500px;
background-color: blue;
margin-left: 100px;
}
.box1 {
width: 200px;
height: 200px;
background-color: pink;
position: fixed;
left:0;
top: 300px;
}
.box2 {
width: 100px;
height: 100px;
background-color: gold;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>