[CSS] Positioning

When elements are positioned, they can be placed in a number of special ways. It is very important to understand positioning rules to place your elements in correct locations.


1. Positioning Rules

The “position” property specifies the type of positioning rule.

  • static : elements are placed in order as block-boxes or inline-boxes (default)
  • absolute : element is positioned with respect to its containing element
  • relative : element is positioned relative to its normal position
  • fixed: element is positioned relative to the browser window. It will not move even if the window is scrolled.

The element’s “display” property plays an important role here.

  • none : no display
  • block : block element like <p> (display as a new line)
  • inline : inline element like <span>


2. Specifying the Position

With the exception of the “static” positioning, you need to specify the location of each element. You can use the following properties:

  • left
  • right
  • top
  • bottom


3. Absolute Positioning

Even though the absolute position is discouraged, it can be useful in some cases. The “div” has 3 child elements.

div { position:absolute; width:200px; height:100px; }
#div1 { background-color:Red;}
#div2 { top:110px; left:10px; background-color:Blue; }
#div3 { top:220px; right:30px; background-color:Green; }


4. z-index

When elements are overlapped, the “z-index” property lets you decide which object places on top of another.

div { position:absolute; width:200px; height:100px; }
#div1 { background-color:Red; z-index:1;}
#div2 { top:30px; left:10px; background-color:Blue; z-index:3; }
#div3 { top:60px; right:30px; background-color:Green; z-index:2; }


5. Relative Positioning

div { position:relative; width:200px; height:100px; }
#div1 { background-color:Red;}
#div2 { top:-100px; left:210px; background-color:Blue; }
#div3 { top:0px; left:0px; background-color:Green; }

Each div moves from its original location. Note that the original space of the “Div2” is preserved.


6. Fixed Positioning

The fixed positioning is even more fixed than the absolute positioning.

div { width:200px; height:100px; }
#div1 { position:absolute; background-color:Red;}
#div2 { position:fixed; top:110px; left:10px; background-color:Blue;}
#div3 { position:absolute; top:150px; left:30px; background-color:Green;}

Make the window small and scroll it up and down. The “div2” will not even move.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s