How to make element position absolute but relative to parent with CSS?

Spread the love

Sometimes, we want to make element position absolute but relative to parent with CSS.

In this article, we’ll look at how to make element position absolute but relative to parent with CSS.

How to make element position absolute but relative to parent with CSS?

To make element position absolute but relative to parent with CSS, we set absolute position on the child elements.

For instance, we write

<div id="father">
  <div id="son1"></div>
  <div id="son2"></div>
</div>

to add divs inside a div.

Then we write

#father {
  position: relative;
}

#son1 {
  position: absolute;
  top: 0;
}

#son2 {
  position: absolute;
  bottom: 0;
}

to make the child elements have absolute position.

The parent div has relative position.

absolute position will position children elements relative to the parent.

Conclusion

To make element position absolute but relative to parent with CSS, we set absolute position on the child elements.

Leave a Reply

Your email address will not be published. Required fields are marked *