CSS position属性的用法(附带实例)
CSS 中的 position 属性用于指定元素的定位方式,属性值包括:
下面的代码演示了元素的相对定位(relative):
下面的代码演示了绝对定位(absolute)的应用:
下面的代码通过固定(fixed)定位方式将工具栏定位在页面的顶部:
- static,静态定位,元素的默认定位方式。
- relative,相对定位。指元素相对于其原始位置的定位,可以使用 top、right、left、bottom 属性定义相对于元素原始位置的偏移量。
- absolute,绝对定位。可以指定元素在其容器中的位置,原点为容器的左上角,可以使用 top、left 属性定义相对于原点的偏移量。如果元素没有明确的容器,会将 html 元素作为元素的容器。此外,绝对定位元素的容器元素定位方式不能是 static。
- fixed,固定定位,以浏览器可视区域作为容器,使用 top、right、left、bottom 属性进行定位。
下面的代码演示了元素的相对定位(relative):
<!doctype html> <html> <head> <meta charset="utf-8" /> <title></title> <style> div {width:200px;height:100px;border:1px solid black;} #div2 { position:relative; top:50px; left:50px; background-color:#ccc; } </style> </head> <body> <div id="div1">div1</div> <div id="div2">div2</div> <div id="div3">div3</div> </body> </html>页面显示效果见下图:

下面的代码演示了绝对定位(absolute)的应用:
<!doctype html> <html> <head> <meta charset="utf-8" /> <title></title> <style> div {width:200px;height:100px;border:1px solid black;} #div2 { position: absolute; top: 50px; left: 50px; background-color: #ccc; } </style> </head> <body> <div id="div1">div1</div> <div id="div2">div2</div> <div id="div3">div3</div> </body> </html>本例中,div2 元素的位置会相对于其容器(body 元素)的左上角定位,页面显示效果见下图:

下面的代码通过固定(fixed)定位方式将工具栏定位在页面的顶部:
<!doctype html> <html> <head> <meta charset="utf-8" /> <title></title> <style> #toolbar { width: 100%; height: 60px; background-color: #ccc; position: fixed; top: 0px; left: 0px; } .page_content { position: relative; top: 60px; background-color: #eee; } .block { width: 200px; height: 300px; border: 1px solid black; } </style> </head> <body> <div id="toolbar">toolbar</div> <div class="page_content"> <div class="block">div1</div> <div class="block">div2</div> <div class="block">div3</div> </div> </body> </html>页面初始效果见下图,滚动页面时,工具栏(toolbar)会固定在页面的顶部。
