59

Is it possible to position a DIV relative to another DIV? I imagine this can be done by first placing it inside of the reference DIV, and then using position: relative. However, I can't figure out how to do this without affecting the contents of the reference DIV. How can I do this properly?

See: http://jsfiddle.net/CDmGQ

2
  • 1
    what are you effecting of the grey div with the red div in that example?
    – Rooster
    Jun 21, 2012 at 17:14
  • I don't understand the question. What do you mean in 'without affecting the contents of the reference DIV'? Can you provide an image of the requested result? Oct 12, 2015 at 7:34

4 Answers 4

104

First set position of the parent DIV to relative (specifying the offset, i.e. left, top etc. is not necessary) and then apply position: absolute to the child DIV with the offset you want.
It's simple and should do the trick well.

1
  • 2
    Doesn't work for me. It works only if I add padding or margin, thus positions the second div below the first one. Oct 12, 2015 at 7:27
15

You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo

#one
{
    background-color: #EEE;
    margin: 62px 258px;
    padding: 5px;
    width: 200px;
    position: relative;   
}

#two
{
    background-color: #F00;
    display: inline-block;
    height: 30px;
    position: absolute;
    width: 100px;
    top:10px;
}​
4

You want to use position: absolute while inside the other div.

DEMO

1
  • 1
    position: absolute alone won't work; the specified offset will refer to the document body and not the parent div (at least in the demo you provided). See my answer.
    – rhino
    Jun 21, 2012 at 17:55
3

you can use position:relative; inside #one div and position:absolute inside #two div. you can see it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.