相对定位的用法是:position: relative;再输入定位变动代码left/right/top/bottom和像素量。
position: relative;
top: 10px;
left: 10px;
输入以下代码时:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.box{
width: 100px;
height: 100px;
background-color: red;
position: relative;
left: 10px;
}
.box2{
width: 100px;
height: 100px;
background-color: #0000FF;
}
</style>
</head>
<body>
<div class="box"></div>
<div class="box2"></div>
</body>
</html>
运行得出如下效果:
当红色方块left100px;右移时:
显示蓝色方块并不会上移,说明红色方块原位置依然占位
当红色方块top50px;下移时:
说明移动后的红色方块不再占位,脱离文档流
当我们输入如下代码时:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.box {
width: 100px;
height: 100px;
position: relative;
}
.box2 {
font-size: 100px;
background-color: #0000FF;
}
</style>
</head>
<body>
<input class="box" type="checkbox" />
<span class="box2">文字</span>
</body>
</html>
显示为:
很明显,复选框与文字并还在一个中心基线上,此时可以对复选框使用相对定位来手动使其对齐