CSS Position

You can define how an element will be positioned on a page with position property.

 

CSS Positioning Methods

It is necessary to position elements appropriately on the web pages to ensure a good layout design. CSS provides several methods for positioning elements. These positioning methods are described in the section below:

 

Static Positioning

The positioning of a static positioned element is according to the normal flow of the page. The positioning of HTML elements is static by default. The elements that are statically positioned are not affected by the left, right, top, bottom, and z-index properties.

Example :

.box {
    padding: 20px;
    background: #7dc765;
}

Try With Example

 

Relative Positioning

The positioning of a relative positioned element is relative to its normal position.

The element's box position is calculated according to the normal flow in the relative positioning scheme. The box is then shifted from its normal position as per the properties — left or right and/or top or bottom.

.box {
    position: relative;
    left: 100px;
}

Try With Example

Note: You can move a relatively positioned element and overlap other elements, but it keeps the space initially reserved for it in the normal flow.

 

Absolute Positioning

The positioning of an absolutely positioned element is relative to the first parent element having a position other than static. If it finds no such element, then the element will be positioned on a page relative to the 'top-left' corner of the browser window. You can further specify the box's offsets using one or more properties top, right, bottom, and left.

The elements that are absolutely positioned are taken out of the normal flow completely, and thus, they take up no space when placing sibling elements. However, an absolutely positioned element can overlap other elements depending on the z-index property value. Also, it can have margins, and they do not collapse with any other margins.

Example :

.box {
    position: absolute;
    top: 200px;
    left: 100px;
}

Try With Example

 

Fixed Positioning

Fixed positioning is absolute positioning's subcategory.

The only difference is that a fixed positioned element is fixed with respect to the viewport of the browser and does not move when scrolled.

Example :

.box {
    position: fixed;
    top: 200px;
    left: 100px;
}

Try With Example

Note: The fixed positioned element is rendered on every page when it comes to print media type. It is fixed with respect to the page box (even in print preview). IE7 and IE8 browsers support the fixed value only if a <!DOCTYPE> is specified.