(2)CSS相对定位元素仍占据原来的空间
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>相对定位</title> <style> #left,#center,#right{ float: left; } #left{ width: 200px; height: 200px; background-color: yellow; } #center{ width: 200px; height: 200px; background-color: #cccccc; position: relative; top: 20px; left: 20px; } #right{ width: 200px; height: 200px; background-color: aquamarine; } </style> </head> <body> <div> <div id="left"></div> <div id="center"></div> <div id="right"></div> </div> </body> </html> 2.CSS绝对定位 position:absolute; (1)采用绝对定位的元素,会寻找离它最近的采用了定位的父元素,并以它为坐标进行定位,如果所有的父元素没有使用定位,则以body为坐标进行定位。
(2)绝对定位元素占用的空间会被其他元素占用。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>绝对定位</title> <style> #left,#center,#right{ float: left; } #left{ width: 200px; height: 200px; background-color: yellow; } #center{ width: 200px; height: 200px; background-color: #cccccc; position: absolute; top: 20px; left: 20px; } #right{ width: 200px; height: 200px; background-color: aquamarine; } </style> </head> <body> <div> <div id="left"></div> <div id="center"></div> <div id="right"></div> </div> </body> </html> 3.固定定位 position: fixed;
将固定元素固定在特定位置,一般加一个z-index,使其不被覆盖
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>固定定位</title> <style> #back{ width: 100px; height: 100px; background-color: yellow; text-align: center; line-height: 100px; position: fixed; bottom: 20px; right: 20px; z-index: 1000; } </style> </head> <body> <div style="height: 1000px"> <div id="back"> 返回顶部 </div> </div> </body> </html>