html

How to Set Position Absolute but Relative to Parent

Setting the absolute position of a child relative to its parent means setting the position of the child element in such a way that the position properties applied to it work in accordance with the area and position of the parent element and not with the whole interface, this is done by adding the position property with the absolute value for the child element or div.

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:

<div id="parent">
    <h1> Parent </h1>

<div id="child1">
    <h1> I am first child!!! </h1>
</div>

<div id="child2">
    <h1> I am the Second child... </h1>
</div>

</div>

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:

#parent {
  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.

About the author

Hadia Atiq

A Software Engineer and Technical Writer passionate about learning and spreading knowledge of the latest technology. I utilize my writing skills to help readers understand the importance and usage of modern technology.