元素的定位属性:包括定位模式和边偏移两部分。
1.边偏移
top: 顶端偏移量,定义元素相对于其父元素上边线的距离。
bottom: 底部偏移量,定义元素相对于其父元素下边线的距离。
left: 左侧偏移量,定义元素相对于其父元素左边线的距离。
right: 右侧偏移量,定义元素相对于其父元素右边线的距离。
2.定位模式
static: 静态定位,默认定位方式,在静态定位状态下,无法通过边偏移属性(top、bottom、left或right)来改变元素位置。静态定位位唯一的用处是取消定位。position: static;
relative: 相对定位,相对于其原文档流的位置进行定位。
absolute: 绝对定位,相对于其上一个已经定位的父元素进行定位。
fixed:固定定位,相对于浏览器窗口进行定位。
相对定位元素相对自己原来的位置,进行位置调整。
box2的相对定位:
<style type="text/css">
div{
width: 200px;
height: 200px;
}
.box1{
background-color: yellowgreen;
}
.box2{
background-color: skyblue;
position: relative;
left: 100px;
top: 150px;
}
.box3{
background-color: lightpink;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</body>
如果一个盒子想进行位置调整,那么就要使用相对定位:
position: relative; 必须先声明自己要相对定位了
特点:不脱标
相对定位不脱标,真实位置在老家,只不过影子出去了,可以到处飘。
在CSS中:
.box2{
background-color: skyblue;
position: relative;
left: 400px;
top: 150px;
margin-bottom: 80px;
}
本质上说此时的蓝色盒子依然位于原来的位置。相对位置相当于浏览器渲染出来的一个图形。
用途
一般不用于做“压盖”效果,就两个作用:
(1)微调元素
(2)绝对定位的参考
<style type="text/css">
.txt{
font-size: 30px;
}
.btn{
position: relative;
top: 4px;
left: 0;
}
</style>
</head>
<body>
<p>
<input type="text" class="txt"/>
<input type="button" value="我是一个按钮" />
</p>
</body>
相对定位可以调整这个按钮的位置
相对定位的位置
可以用left、right来描述盒子的左右移动;
可以用top、bottom来描述盒子的上下移动;
向右下移动:
position: relative;
top: 10px;
left: 40px
向左下移动:
position: relative;
right: 100px;
top: 100px;
向左上移动:
position: relative;
right: 100px;
bottom: 100px;
负数就是相反的方向,所以向右上移动:
position: relative;
top: -200px;
right: -200px;
向右上移动:
position: relative;
right: -300px;
bottom: 300px;