Default value for CSS position property is static.
Property Value
The following table provides a list of values for CSS position property.
Value
Explanation
relative
The element is positioned according to the normal flow of the document, and then offset relative to itself based on the values of top, right, bottom, and left.
absolute
The element is positioned relative to its first positioned (not static) ancestor element.
fixed
The element is positioned relative to the browser window.
static
The element is positioned according to the normal flow of the document. The top, right, bottom, left, and z-index properties have no effect.
sticky
The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block.
Using fixed
In the following example, we will demonstrate how CSS position:fixed works.
Example
HTML Online Editor
<!DOCTYPE html>
<htmllang="en-US">
<head>
<style>
body{
height: 800px;
}img{
position: fixed;
}
</style>
</head>
<body>
<h1>CSS position Property</h1>
<p>This is first paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
<div>
<imgsrc="apple.png">
</div>
</body>
</html>
In the following example, we will demonstrate how CSS position:sticky works.
Example
HTML Online Editor
<!DOCTYPE html>
<htmllang="en-US">
<head>
<style>
body{
height: 1500px;
}div{
position: -webkit-sticky;
position: sticky;
top: 0;
padding: 5px;
background-color: #bfbfbf;
border: 2pxsolidblack;
}
</style>
</head>
<body>
<h1>CSS position Property</h1>
<p>This is first paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
<div>
I will stick, when I reach the top of the page.
</div>
</body>
</html>
In the following example, we will demonstrate how to change the CSS position property of an element using JavaScript.
Example
HTML Online Editor
<!DOCTYPE html>
<htmllang="en-US">
<head>
<style>
body{
height: 1500px;
}div{
position: -webkit-sticky;
position: sticky;
top: 0;
padding: 5px;
margin-bottom: 15px;
background-color: #bfbfbf;
border: 2pxsolidblack;
}
</style>
</head>
<body>
<h1>CSS position Property</h1>
<p>This is first paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
<div>
I will stick, when I reach the top of the page.
</div>
<buttononclick="myFunction()">Click Me</button>
<script>
varx=document.getElementsByTagName("div")[0];
functionmyFunction(){
x.style.position="static";
}
</script>
</body>
</html>