Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position one element relative to another in CSS

I want to position four divs relative to another. I have a rectangle div, and I want to insert 4 divs at its corners. I know that CSS has an attribute "position:relative", but this is relative to the normal position of that element. I want to position my divs not relative to their normal position, but relative to another element (the rectangle). What should I do?

like image 731
Babak Mehrabi Avatar asked Jun 22 '12 06:06

Babak Mehrabi


People also ask

How do you set position relative to other element in CSS?

Have your four divs nested inside the target div, give the target div position: relative , and use position: absolute on the others. And this CSS should work: #container { position: relative; } #container > * { position: absolute; } . left { left: 0; } .

How do you position a div relative to another element?

We can make the dialog div be position relative to the parent div by first making it a child of the parent div and then setting the parent position to relative. The parent is set to relative position and the dialog has absolute position. Now the dialog div is rendered over the parent div.

How does position relative work in CSS?

An element with position: relative; is positioned relative to its normal position. Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.

Is position inherited in CSS?

As it can be observed in the above example, the position defined in the style is inherit, but the computed position value is relative. This is because inherit sets the value to that of its parent element.


1 Answers

position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static.

Have your four divs nested inside the target div, give the target div position: relative, and use position: absolute on the others.

Structure your HTML similar to this:

<div id="container">   <div class="top left"></div>   <div class="top right"></div>   <div class="bottom left"></div>   <div class="bottom right"></div> </div> 

And this CSS should work:

#container {   position: relative; }  #container > * {   position: absolute; }  .left {   left: 0; }  .right {   right: 0; }  .top {   top: 0; }  .bottom {   bottom: 0; }  ... 
like image 151
Blender Avatar answered Oct 15 '22 15:10

Blender