Change the position of a <div> element from relative to absolute:
document.getElementById("myDIV").style.position = "absolute";
Click the button to change the position property of the DIV element:
<!DOCTYPE html> <html> <head> <style> #myDIV {//from ww w. jav a 2s . co 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 DIV element is placed 20 pixels from the top of its original position.</p> P:Click the button to set the position property to "absolute" and see what happens.</p> <p>It will then be placed 20 pixels from the top the page.</p> </div> <script> function myFunction() { document.getElementById("myDIV").style.position = "absolute"; } </script> </body> </html>
The position property sets or gets the type of positioning method used for an element.
Property Values
Value | Description |
---|---|
static | Elements renders in order, as they appear in the document flow. default . |
absolute | positioned relative to its first positioned non-static ancestor element |
fixed | positioned relative to the browser window |
relative | positioned relative to its normal position |
sticky | positioned based on the user's scroll position |
initial | Sets this property to its default value. |
inherit | Inherits this property from its parent element. |
The position property returns a String representing the position type of an element.