The time we are designing a HTML page for more complex layout we do refer position using CSS. Basically this is used to position the HTML elements. There are 6 possible values for position property in CSS. By default position is static. According to our requirements we can apply absolute, relative, fixed, initial & inherit values to the position property in CSS.
Position: static;
This is the default value for position property. By declaring position static it will render the HTML elements in order to the document flow.
Position: absolute;
Position absolute is the most trickiest positioning value. Let us take example to understand position absolute. In below example I am using position absolute for a div inside the div which is position relative.
<!DOCTYPE html> <html> <head> <title>Using Position Absolute</title> <style type="text/css"> .posRelative { position: relative; top: 100px; left: 100px; } .posAbsolute { position: absolute; top: 100px; left: 100px; } </style> </head> <body> <div class="posRelative"> <div class="posAbsolute"> This is the div where we applied position absolute. </div> </div> </body> </html>
This will give us first div in 100px left & 100px from top position. The second div is applied with position absolute. In real-time the second div will appear 100px left & top from the parent div.
If i am declaring the parent div position static then child div with position absolute will show in 100px top & left from the top left corner of the browser window. Try with the example below.
<!DOCTYPE html> <html> <head> <title>Using Position Absolute</title> <style type="text/css"> .posStatic { position: static; top: 100px; left: 100px; } .posAbsolute { position: absolute; top: 100px; left: 100px; } </style> </head> <body> <div class="posStatic"> <div class="posAbsolute"> This is the div where we applied position absolute. </div> </div> </body> </html>
Position: fixed;
Using position fixed we can set position of our HTML element from the top left corner of browser window.
Position: relative;
Using position relative the position is relative to its normal position. If I am declaring top:100px it will take the element to 100px down.
Position: initial;
Position initial reset the position of an element to default value.
Position: inherit;
Using position inherit we can inherits this property from parent element. You can access CSS position property using JavaScript. The syntax we need to use is object.style.position=”fixed”.