Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position DIV relative to another DIV?

Tags:

html

css

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

like image 663
Nathanael Avatar asked Jun 21 '12 17:06

Nathanael


People also ask

How do you set a div position relative to another div?

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.

How do you position an element relative to another?

In position: relative , the element is positioned relative to itself. However, an absolutely positioned element is relative to its parent. An element with position: absolute is removed from the normal document flow. It is positioned automatically to the starting point (top-left corner) of its parent element.

Can a div be position absolute and relative?

If you position it as absolute , then you're positioning it relative to its closest ancestor which is fixed or relative ... Clearly, nothing can be absolute and relative at the same time. Either you want the element to position itself based on another ancestor's position or based on the page flow.

What is position relative relative to?

position: relative; changes the position of the element relative to the parent element and relative to itself and where it would usually be in the regular document flow of the page. This means that it's relative to its original position within the parent element.


2 Answers

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.

like image 178
rhino Avatar answered Oct 17 '22 00:10

rhino


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; }​ 
like image 40
Nishu Tayal Avatar answered Oct 17 '22 02:10

Nishu Tayal