Positioning in CSS

·

2 min read

As a developer, once in your lifetime, you would've tried to position an element and see your web page break.

Let's position that site better with these methods. Image

Position: absolute;

Gives you the control of the element to be placed anywhere in the page specified top, bottom, left and right, relative to the main page, regardless of the flow of the document and other elements.

div {
      position: absolute;
      // styles
}

Position: relative;

An element is positioned relatively whenever the child elements has to be positioned relative to its parent element rather than the document itself.

.parent {
      position: relative;
      // styles
}
.child {
     position: absolute;
     // positioned wrt .parent
}

Position: fixed;

Attaches an element to a fixed position and locks it to the viewport. The element positioned as fixed, stays intact at that position regardless or other elements. Usually used for navigation bars in a landing page.

.navbar {
      position: fixed;
      top: 0;
      //styles
}

Position: static;

Default type of positioning applied to the elements. The elements follow the flow of document and placement of one element is affected to another.

div {
      position: static;
      //styles
}

Position: sticky;

Sticky element is positioned based on the nearest scroll parent.The offset does not affect the position of any other elements.

div {
      position: sticky;
      //styles
}

Fun facts

z-index works only on positioned elements.

Whenever top, bottom, left and right has same values it can replaced by inset.

Conclusion

This was my learnings about positions in CSS. There are endless articles and resources to learn from. Positioning frogs helped me apply the learning and understand it better. Hope this helps you too.