相对定位
1.默认情况
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div{ margin: 10px; padding: 5px; font-size: 10px; line-height: 20px; } #father{ border: 1px solid sandybrown; padding: 0; } #first{ background-color: #88ec85; border: 1px dashed #9ac4d5; } #second{ background-color: #FFE53B; border: 1px dashed #18f8c3; } #third{ background-color: #e4eef1; border: 1px dashed #f57474; } </style> </head> <body> <div id="father"> <div id="first">第一个盒子</div> <div id="second">第二个盒子</div> <div id="third">第三个盒子</div> </div> </body> </html>
2.相对定位
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--相对定位 相对于自己原来的位置进行偏移~ --> <style> body{ padding: 20px; } div{ margin: 10px; padding: 5px; font-size: 10px; line-height: 20px; } #father{ border: 1px solid sandybrown; padding: 0; } #first{ background-color: #88ec85; border: 1px dashed #9ac4d5; position: relative;/*相对定位 上下左右*/ top: -20px;/*距离原来的位置向上偏离20px*/ left: 20px; } #second{ background-color: #FFE53B; border: 1px dashed #18f8c3; } #third{ background-color: #e4eef1; border: 1px dashed #f57474; position: relative; bottom: -20px;/*!!!这样理解:对于设定的方向,负号表示向设定的方向移动,!!!*/ right: 10px; } </style> </head> <body> <div id="father"> <div id="first">第一个盒子</div> <div id="second">第二个盒子</div> <div id="third">第三个盒子</div> </div> </body> </html>
top: -20px;
left: 20px;
bottom: -20px;
right: 10px;
练习:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #box{ width: 300px; height: 300px; border: 2px solid red; padding: 10px; } a{ width: 100px; height: 100px; display: block; background-color: lightpink; color: white; line-height: 100px; text-align: center; text-decoration: none; } a:hover{ background-color: aqua; } .a2,.a4{ position: relative; left: 200px; top: -100px; } .a5{ position: relative; left: 100px; top: -300px; } </style> </head> <body> <div id="box"> <a href="#" class="a1">链接1</a> <a href="#" class="a2">链接2</a> <a href="#" class="a3">链接3</a> <a href="#" class="a4">链接4</a> <a href="#" class="a5">链接5</a> </div> </body> </html>