Amir Shabani Amir Shabani - 1 year ago 102
CSS Question

position relative css tricks

I am a new web designer so I decided to analysis other HTML,CSS codes. I found a weird thing. Why should some developers use position: relative without any top,left,right,bottom?

Is there any hack or trick in it?

like this:

.main {
position: relative;
margin: 0;
overflow-x: hidden;

Answer Source

Position relative is useful because elements with a position set (thats not static) can be used to position other elements inside it. Because relative maintains things in the flow of the page, there is no need to set top, left, right or bottom values. If, for example, you want to use absolute positioning inside a box, you give the outer box position: relative. This means any element inside it will take its positioning from the top left of the relative outer box. If the parent element does not have positioning set (or inherited), it will position itself to the viewport instead of a box. So an element that is not wrapped in a relative wrapper will position itself based on the page, while a relative wrapper means it will position relative to the wrapper.

So thats the hack and thats why you will see it often. In short: 'relative' keeps that element in the flow, while children with other positioning will now be positioned relative to this element.

Quick Example

h1 { width: 100%; }
#relative { position: relative; width: 100%; }
.position { position: absolute; top: 20px; left: 20px; border: 1px solid #000;}
<div id="absolute" class="position">Position based on page</div>
<div id="relative"><div class="position">Position based on box</div></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download