一.相对定位
相对定位:相对本元素原来的位置
用法:
position: relative;
top: -20px;
left: 20px;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
margin: 10px;
padding: 5px;
font-size: 12px;
line-height: 25px;
}
#father{
border: 1px solid indianred;
}
#first{
background: #f1e7e7;
border: 1px dashed #82b4bd;
position: relative; /*相对定位:相对本元素原来的位置*/
top: -20px;
left: 20px;
}
#second{
background: #ba6969;
border: 1px dashed #5ccd5e;
}
#third{
background: #d41c1c;
border: 1px dashed #a2cd5c;
}
</style>
</head>
<body>
<div id="father">
<div id="first">第1个盒子</div>
<div id="second">第2个盒子</div>
<div id="third">第3个盒子</div>
</div>
</body>
</html>
效果:
相对定位练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box{
width: 300px;
height: 300px;
padding: 10px;
border: 2px solid red;
}
a{
width: 100px;
height: 100px;
background-color: pink;
text-decoration: none;
line-height: 100px;
text-align: center;
color: white;
display: block;
}
a:hover{
background-color: cornflowerblue;
}
.a1{
position: relative;
}
.a2{
position: relative;
top: -100px;
left: 200px;
}
.a3{
position: relative;
}
.a4{
position: relative;
top: -100px;
left: 200px;
}
.a5{
position: relative;
top: -300px;
left: 100px;
}
</style>
</head>
<body>
<div id="box">
<a class="a1" href="#">链接1</a>
<a class="a2" href="#">链接2</a>
<a class="a3" href="#">链接3</a>
<a class="a4" href="#">链接4</a>
<a class="a5" href="#">链接5</a>
</div>
</body>
</html>
二.绝对定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
margin: 10px;
padding: 5px;
font-size: 12px;
line-height: 25px;
}
#father{
border: 1px solid indianred;
}
#first{
background: #f1e7e7;
border: 1px dashed #82b4bd;
position: absolute;
left: 10px;
top: 300px;
}
#second{
background: #ba6969;
border: 1px dashed #5ccd5e;
}
#third{
background: #d41c1c;
border: 1px dashed #a2cd5c;
}
</style>
</head>
<body>
<div id="father">
<div id="first">第1个盒子</div>
<div id="second">第2个盒子</div>
<div id="third">第3个盒子</div>
</div>
</body>
</html>
三.固定定位 fixed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
height: 1000px;
}
div:nth-of-type(1){/*绝对定位,相对于浏览器*/
width: 100px;
height: 100px;
background: red;
position: absolute;
right: 0;
bottom: 0;
}
div:nth-of-type(2){/*固定定位*/
width: 50px;
height: 50px;
background: yellow;
position: fixed;
right: 0;
bottom: 0;
}
</style>
</head>
<body>
<div>div1</div>
<div>div2</div>
</body>
</html>