Stil position egenskap

Definition och användning

position Typ av positioneringsmetod för elementet (statisk, relativ, absolut eller fast) definieras eller returneras av egenskapsinställningar.

Se också:

CSS tutorial:CSS positionering

CSS referenshandbok:position attribute

Instance

Example 1

Change the positioning of the <div> element from relative to absolute:

document.getElementById("myDIV").style.position = "absolute";

Try it yourself

Example 2

Use different positioning types:

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

Try it yourself

Example 3

Returns the positioning of the <h2> element:

alert(document.getElementById("myH2").style.position);

Try it yourself

Syntax

Return the position attribute:

object.style.position

Set the position attribute:

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

Attribute value

Value Description
static The elements are displayed in the order they appear in the document flow. Default.
absolute The element is positioned relative to its first positioned (non-static) ancestor element.
fixed The element is positioned relative to the browser window.
relative

The element is positioned relative to its normal position.

Therefore, "left:20" increases the left position of the element by 20 pixels.

sticky

The element is positioned based on the user's scroll position.

Sticky elements switch between relative and fixed based on the scroll position.

It is relatively positioned until it encounters the given offset position in the viewport - then it 'sticks' at the appropriate position (such as position:fixed).

Note:Not supported in IE/Edge 15 or earlier versions. Safari has supported the Webkit prefix since version 6.1.

initial Sets this property to its default value. See initial.
inherit Inherits this property from its parent element. See inherit.

Technical details

Default value: static
Return value: A string representing the element's positioning type.
CSS version: CSS2

Webbläsarstöd

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Stöd Stöd Stöd Stöd Stöd