四种Position属性
static(默认),relative(相对定位),absolute(绝对定位)和fixed(固定定位)
static和relative会占文档流空间,absolute和fixed不会占据文档流空间。
**解释:**就是absolute和fixed是可以浮动在其他的元素之上的,可以放到任何的位置,无论该位置是否有元素。
static
浏览器采用的的默认定位。
relative
相对定位,此属性一般和absolute结合使用,父元素使用relative,子元素使用absolute,达到子元素可以在父元素中任意位置浮动的效果,当此属性单独使用时,加上top表示和正常位置的元素的顶部偏移位置。
absolute
绝对定位,默认的父级元素是body,所以如果父元素未使用position:relative属性,则将body作为父级元素。
fixed
固定定位,相对于浏览器的当前浏览窗口定位,会一直出现在窗口中,多用于顶部导航栏,底部导航栏,跟随的广告位。
注意
1.relative,absolute,fixed都要结合top,bottom,left, right来使用,但是同时top和bottom只能出现一个,left和right只能出现一个。
2.static无法结合top,bottom,left, right和z-index来使用。只有其他三个属性可以使用。
3.当没有z-index时,会根据元素出现的次序来决定上下层关系。
以下是属性的使用例子。
例子
用例代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>position练习</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
}
.all {
position: relative;
}
.content {
position: absolute;
top: 50px;
z-index: -1;
position: relative;
margin: 0 auto;
width: 1000px;
}
.height50 {
width: 1000px;
height: 50px;
background-color: lightblue;
}
.height100inbottom {
width: 1000px;
height: 100px;
background-color: lightblue;
}
.div1 {
position: absolute;
right: 0;
width: 200px;
height: 200px;
background-color: red;
text-align: center;
line-height: 200px;
}
.div2 {
width: 300px;
height: 300px;
background-color: green;
text-align: center;
line-height: 300px;
}
.div3 {
width: 1000px;
height: 1000px;
background-color: gray;
}
.left {
position: fixed;
left: 0;
top: 200px;
width: 500px;
height: 400px;
background-color: lightgreen;
}
.right {
z-index: -1;
position: fixed;
right: 0;
top: 200px;
width: 500px;
height: 400px;
background-color: lightgreen;
}
.navbar {
position: fixed;
top: 0;
width: 100%;
height: 50px;
background-color: yellow;
line-height: 50px;
text-align: center;
}
.tabbar {
position: fixed;
bottom: 0;
width: 100%;
height: 50px;
background-color: yellow;
line-height: 50px;
text-align: center;
}
</style>
</head>
<body>
<div class="all">
<div class="navbar">导航栏</div>
<div class="content">
<div class="left">
left
</div>
<div>
<div class="height50">
50的高,使用了top:50来控制和顶部导航栏的距离,避免被顶部导航栏隐藏掉这部分内容
</div>
<div class="div1">
1
</div>
<div class="div2">
2
</div>
<div class="div3">
3
</div>
<div class="height100inbottom">
高度为100px,但是却只显示了一半,被底部tabbar隐藏了50px
</div>
</div>
<div class="right">
right
</div>
</div>
<div class="tabbar">
底部导航栏高度为50px
</div>
</div>
</body>
</html>