CSS定位
1. 相对定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
padding:20px;
}
div{
margin:10px;
padding: 5px;
font-size:12px;
line-height:25px;
}
#father{
border:1px solid black;
padding:0;
}
#first{
background-color: darkseagreen;
border:1px dashed #dc5f45;
position:relative;
top:-20px;
left:20px;
}
#second{
background-color: rebeccapurple;
border:1px dashed #dc0100;
}
#third{
background-color: #bad8dc;
border:1px dashed #b8dc9c;
position:relative;
bottom:10px;
}
</style>
</head>
<body>
<div id="father">
<div id="first">第一个盒子</div>
<div id="second">第二个盒子</div>
<div id="third">第二个盒子</div>
</div>
</body>
</html>
相对定位:相对于原来的位置进行偏移
position:relative;
#first{
background-color: darkseagreen;
border:1px dashed #dc5f45;
position:relative;
top:-20px;
left:20px;
}
相对定位仍然在标准文档流中,原来的位置被保留。
案例1:
<!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;
text-decoration: none;
background: pink;
line-height: 100px;
text-align: center;
color: white;
display:block;
}
a:hover{
background: #b8dc9c;
}
.a2,.a4{
position: relative;
left:200px;
top:-100px;
}
.a5{
position:relative;
left:100px;
top:-300px;
}
</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>
2. 绝对定位
- 在没有父级元素定位的前提下,相对于浏览器定位
- 假设父级元素存在定位,相对于父级元素进行偏移
|