i

Learn HTML and CSS in 10 Days

Uniquely Positioning Layouts

Every web developer wants to position an element very precisely, but the inline-block and float element can't perform the trick all the time. But to do this, we have our 'position' property. This property helps in identifying the positioning of an element on a web page and regardless of whether it will show up inside the typical progression of a document. This is used with the help of box offset properties – right, left, top, and bottom.

By default, all the elements come with the value as 'static' for their 'position' property. This value is generally overwritten by ‘relative’ and ‘absolute’ value. Let’s check them out.

Relative Positioning

The ‘position’ property that has the value as ‘relative’ provides elements to show up inside the normal stream of a page, leaving space for elements as planned while not enabling other elements to flow around it.

CSS

div {

  height: 100px;

  width: 100px;

}

.offset {

  left: 20px;

  position: relative;

  top: 20px;

}

The element that has the class value as 'offset' consists of the position value as 'relative' along with two box offset properties i.e., top and left. This helps in preserving the original element's position; thus, other elements will not be moved into this space. In addition to that, the offset properties shift the element 20 pixels to the top and left of its original location.

Absolute Positioning

In this kind of positioning, the element will not be appearing within the normal flow of the page, and the original position and space of the element will not be kept preserved.

CSS

section {

  position: relative;

}

div {

  position: absolute;

  right: 20px;

  top: 20px;

}

In the above code the

element is positioned as relative. It does not contains any box offset properties. Theelement with the offset class comes has a position value as absolute. Theelement will be placed in relation with theelement as theelement is the nearest situated parent element.