目录

style position 属性

示例

将 <div> 元素的位置从相对位置更改为绝对位置:

document.getElementById("myDIV").style.position = "absolute";
亲自试一试 »

描述

Position 属性设置或返回用于元素的定位方法的类型(静态、相对、绝对或固定)。


浏览器支持

Property
position Yes Yes Yes Yes Yes

语法

返回位置属性:

object.style.position

设置位置属性:

object.style.position = "static|absolute|fixed|relative|sticky|initial|inherit"

属性值

Value Description
static Elements renders in order, as they appear in the document flow. This is default.
absolute The element is positioned relative to its first positioned (not static) ancestor element
fixed The element is positioned relative to the browser window
relative The element is positioned relative to its normal position, so "left:20" adds 20 pixels to the element's LEFT position
sticky The element is positioned based on the user's scroll position

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

Note: Not supported in IE/Edge 15 or earlier. Supported in Safari from version 6.1 with a Webkit prefix.
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit


技术细节

默认值: 静止的
返回值: String,表示元素的位置类型
CSS版本 CSS2

更多示例

示例

使用不同的位置类型:

function myFunction(x)  {
  var whichSelected = x.selectedIndex;
  var posVal = x.options[whichSelected].text;
  var elem = document.getElementById("myDiv");
  elem.style.position = posVal;
}
亲自试一试 »

示例

返回 <h2> 元素的位置:

alert(document.getElementById("myH2").style.position);
亲自试一试 »

相关页面

CSS教程:CSS定位

CSS 参考:位置属性