我们可以使用css的position属性来设置元素的定位类型,postion的设置项如下:
relative 生成相对定位元素,元素所占据的文档流的位置不变,元素本身相对文档流的位置进行偏移
absolute 生成绝对定位元素,元素脱离文档流,不占据文档流的位置,可以理解为漂浮在文档流的上方,相对于上一个设置了相对或者绝对或者固定定位的父级元素来进行定位,如果找不到,则相对于body元素进行定位。
fixed 生成固定定位元素,元素脱离文档流,不占据文档流的位置,可以理解为漂浮在文档流的上方,相对于浏览器窗口进行定位。
static 默认值,没有定位,元素出现在正常的文档流中,相当于取消定位属性或者不设置定位属性
inherit 从父元素继承 position 属性的值
定位元素特性
绝对定位和固定定位的块元素和行内元素会自动转化为行内块元素
定位元素层级
定位元素是浮动的正常的文档流之上的,可以用z-index属性来设置元素的层级
典型定位布局
1、固定在顶部的菜单
2、水平垂直居中的弹框
3、固定的侧边的工具栏
4、固定在底部的按钮
这里列三个实例,分别为相对定位、绝对定位和固定定位。
相对定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>相对定位</title>
<style type="text/css">
.box1{
height: 200px;
background-color: red;
position: relative;
}
.box2{
width: 200px;
height: 200px;
background-color: yellow;
position: relative;
当开启了元素的定位(position属性值是一个非static的值)时,可以通过left right top bottom四个属性来设置元素的偏移量
left:元素相对于其定位位置的左侧偏移量
right:元素相对于其定位位置的右侧偏移量
top:元素相对于其定位位置的上边的偏移量
bottom:元素相对于其定位位置下边的偏移量
通常偏移量只需要使用两个就可以对一个元素进行定位,
一般选择水平方向的一个偏移量和垂直方向的偏移量来为一个元素进行定位
*/
left: 100px;
top: 200px;
}
.box3{
width: 200px;
height: 200px;
background-color: yellowgreen;
}
.s1{
position: relative;
width: 200px;
height: 200px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<span class="s1">我是一个span</span>
</body>
</html>
绝对定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绝对定位</title>
<style type="text/css">
.box1{
width: 200px;
height: 200px;
background-color: red;
}
.box2{
width: 200px;
height: 200px;
background-color: yellow;
position: absolute;
/*left: 100px;
top: 100px;*/
}
.box3{
width: 300px;
height: 300px;
background-color: yellowgreen;
}
.box4{
width: 300px;
height: 300px;
background-color: orange;
/*开启box4的相对定位*/
/*position: relative;*/
}
.s1{
width: 100px;
height: 100px;
background-color: yellow;
/*开启绝对定位*/
position: absolute;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box5">
<div class="box4">
<div class="box2"></div>
</div>
</div>
<div class="box3"></div>
<span class="s1">我是一个span</span>
</body>
</html>
固定定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>固定定位</title>
<style type="text/css">
.box1{
width: 200px;
height: 200px;
background-color: red;
}
.box2{
width: 200px;
height: 200px;
background-color: yellow;
position: fixed;
left: 0px;
top: 0px;
}
.box3{
width: 200px;
height: 200px;
background-color: yellowgreen;
}
</style>
</head>
<body style="height: 5000px;">
<div class="box1"></div>
<div class="box4" style="width: 300px; height: 300px; background-color: orange; position: relative;">
<div class="box2"></div>
</div>
<div class="box3"></div>
</body>
</html>