The position
property sets or gets the type of
positioning method used for an element in static, relative, absolute or fixed position.
position |
Yes | Yes | Yes | Yes | Yes |
Return the position property:
var v = object.style.position;
Set the position property:
object.style.position='static|absolute|fixed|relative|initial|inherit'
The property values are listed in the following table.
Value | Description |
---|---|
static | The element is laid out as normal (default value). |
absolute | Positioned relative to its first non-static positioned ancestor element |
fixed | Positioned relative to the browser window |
relative | Positioned relative to its normal position, "left:10px" adds 10 pixels to the element's left position |
inherit | Inherit the position property from the parent element |
You use the top
, bottom
,
left
, and right
properties to offset the element.
We can use the fixed value to make the element stay at the same location during the rest of the content scrolling up or down.
Default Value: | static |
---|---|
Return Value: | A string representing the position type |
CSS Version | CSS2 |
The following code shows how to change the position of a <div> element from relative to absolute:
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {<!--from w w w. j a v a2 s .c o m-->
border: 1px solid black;
background-color: lightblue;
width: 300px;
height: 300px;
position: relative;
top: 20px;
}
</style>
</head>
<body>
<button onclick="myFunction()">test</button>
<div id="myDIV">
<p>this is a test.</p>
<p>this is a test.</p>
<p>this is a test.</p>
</div>
<script>
function myFunction() {
document.getElementById("myDIV").style.position = "absolute";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to use different position types.
<!DOCTYPE html>
<html>
<body>
<div id="myDiv" style="top:50px;left:100px;">I am a div element.</div>
<!--from w ww . j av a 2 s.c o m-->
<select onchange="myFunction(this);" size="4">
<option>absolute
<option>fixed
<option>static
<option>relative
</select>
<script>
function myFunction(x) {
var whichSelected = x.selectedIndex;
var posVal = x.options[whichSelected].text;
var elem = document.getElementById("myDiv");
elem.style.position=posVal;
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to get the position of a <h2> element
<!DOCTYPE html>
<html>
<body>
<!-- w ww . j ava 2 s . c om-->
<h2 id="myH2" style="position:absolute;left:100px;top:150px;">This is a heading</h2>
<button type="button" onclick="myFunction()">get</button>
<script>
function myFunction() {
console.log(document.getElementById("myH2").style.position);
}
</script>
</body>
</html>
The code above is rendered as follows: