How to position an element relative to its container with CSS?

Spread the love

Sometimes, we want to position an element relative to its container with CSS.

In this article, we’ll look at how to position an element relative to its container with CSS.

How to position an element relative to its container with CSS?

To position an element relative to its container with CSS, we set position to absolute.

For instance, we write

<div id="container">
  <div id="box">absolute</div>
</div>

to add nested divs.

Then we write

#container {
  position: relative;
  border: 1px solid red;
  height: 100px;
}

#box {
  position: absolute;
  top: 50px;
  left: 20px;
}

to set position to absolute fot the inner div to place the div relative to its parent.

We set top to the number of pixels relative to the parent vertically.

And we set left to the number of pixels relative to the parent horizontally.

Conclusion

To position an element relative to its container with CSS, we set position to absolute.

Leave a Reply

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