The CSS position properties help you to position your HTML element. You can put any HTML element at whatever location you like. It can also place an element behind another.
There are five different position values:
HTML elements are positioned static by default. Static positioned elements are not affected by the left, right, top and bottom properties.
position: relative helps an element to change its position from original to new position, using left, right, top and bottom properties. The element will be positioned according to the parent element.
Example 1: Change the HTML element's position using CSS relative and top properties.
<style> div{ padding: 15px; } .div1{ width: 500px; height: 300px; background: #ff7; margin: auto; font: 18px arial; } .div2{ width: 150px; height: 100px; background: #ff8888; position: relative; left: 100px; top: 100px; line-height: 1.4; } </style> <body> <div class="div1"> Some text in parent div <div class="div2"> Child div moved left 100px and top 100px. </div> </div> </body>
An HTML element with absolute position will move according to HTML body. However, if you want to position according to its parent, then specify position relative to the parent element.
Example 2: CSS Absolute Position
An element, with a fixed position, will not move even if the window is scrolled.
Example 3: CSS Fixed Position
The z-index property specifies the order in which the elements should be displayed when two or more elements occupy the same area on the page. Using the z-index style property, you can specify how an element should appear when overlapping with another element. An element with the highest z-index value will be on the top of all the other elements. If two elements have the same z-index value, then their source order determines their order of appearance. The last element is on top of the previous element. Value of z-index can be positive or negative.
Example 4: CSS z-index property
Example 5: CSS z-index property