Setting Absolute Position Relative to Parent Div
The position can be set according to the parent div by adding position properties in the CSS style element.
Let’s discuss this with the help of a simple example where there is a parent div and two child divs associated with it:
In the above code snippet, there is a parent div, and it has two child divs:
- There is the div tag that has the id declared as “parent,” and inside the div, there is a <h1> heading as the content to be displayed inside the div area.
- Then, there is the child div inside the parent div that has the id declared as “child1“.
- Similarly, there is another child div tag that declares the id of the div as “child2“.
This will display the following results:
To set the absolute position of the “child1” and “child2” relevant to the parent div, it is just required to add the CSS position absolute properties for the child divs and position relative property for the parent div:
position: relative;
}
#child1 {
position: absolute;
}
#child2 {
position: absolute;
}
The heading created in the parent div will not move, but those of the child divs change their position relative to the position of the parent div. This will display the following interface in the output:
This is how we can set the position absolute relative to the parent div.
Conclusion
The absolute position of the child divs in an HTML document can be set relative to their parent div in such a way that the CSS properties added for the child divs implement according to the position of their parent div. This is done by adding the absolute position property in the CSS style element referring to the class or id of the child div.