HTML DOM Style position Property

HTMLDOMWeb DevelopmentFront End Technology

The HTML DOM Style position property returns and modify the positioning method used by an HTML element in an HTML document.

Syntax

Following is the syntax −

1. Returning position

object.position

2. Modifying position

object.position = “value”

Here, value can be −

Sr.NoValue & Explanation
1initial
It set this property value to its default value.
2inherit
It inherits this property value from its parent element.
3static
In this, the element will render in the order as they appear in document flow.
4absolute
In this, the element will position relative to its first positioned ancestor element in the document.
5fixed
In this, the element will position relative to the browser window in the document.
6relative
In this, the element will position relative to its normal position in the document.
7sticky
In this, the element will position according to the user’s scroll position in the document

Let us see an example of HTML DOM Style position Property −

Example

Live Demo

<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      height: 100vh;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 2px;
      width: 40%;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem 0;
   }
   .square {
      width: 100px;
      height: 100px;
      background: #db133a6b;
      top: 150px;
      left: 50%;
   }
   .show {
      font-size: 1.2rem;
      margin: 1rem 0;
   }
</style>
<body>
<h1>DOM Style position Property Demo</h1>
<div class='square'></div>
<button onclick="set()" class="btn">Set Position</button>
<script>
   function set() {
      document.querySelector('.square').style.position = "fixed";
   }
</script>
</body>
</html>

Output

Click on “Set Position” button to set the position of pink square.

raja
Published on 23-Sep-2019 11:21:24
Advertisements