Menu

How to Position an element absolute to a div

June 12, 2015 - Blog, Lessons, Web Development
How to Position an element absolute to a div

If you are learning ho to be a web developer, fantastic! I remember there were three things that had me stumped when I was learning.

  1. floating elements and clearing floats
  2. absolute and relative positioning
  3. z-index

Once you grasp that you could totally rock the world as a junior frontend developer!

I thought I’d create a quick screencast that will show users how to position a span absolute to a containing div. This will help those who are a bit confused about it as it is using very simple markup. Sometimes it is best to just simplify everything on the page if you want to learn a new technique. Once the lightbulb moment hits you can go ahead and add more elements.

The video consists of me creating 2 divs with content within it. The second div has a span. I want to move it to the top right hand corner of that div by using absolute positioning.

In the first instance I set the span to have a top of 0px and a right of 0px which should mean that the span will be 0px to the top of the div and 0px to the right of the div. Right? Wrong.

We have just positioned that element to the page as it doesn’t know what it is relative to. If we then add position:relative to the containing div we will see that our element is positioned the way we want!

Have a look at the video. I hope it helps you in your quest to be a frontend developer.

Leave a Reply

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