Positioning in CSS

USAMA USMANUSAMA USMAN
2 min read

Positioning in CSS

There are five types of positioning in CSS

  • Static position

  • Fixed position

  • Sticky position

  • Relative position

  • Absolute position

Static position

Static is the by-default position in CSS. Properties of positons like top, left, and right, do not work in static position instead we have to use margins to move objects.

Fixed position

Fixed position is just like static position in CSS but it accepts properties like top, left, right and bottom to move objects. Fixed-positioned object stay at some position on scrolling or we can say that scrolling does not affect fixed-positioned object.

.header {
    position: fixed;
    top: 50px;
    left: 10%;
}

Sticky position

Sticky position is usually used in navbar so when the user scrolls, navbar sticks to some position. Sticky position only works when you define, after how much pixel you have to stick on some position.

.navbar {
    position: sticky;
    margin-top: -100px;
}

Relative position

The behaviour of relative position is something like fixed position but on scrolling, it does not fix to some position and moves up.

.image {
    position: relative;
    top: 100px;
    left: 200px;
}

Absolute position

Absolute position is used to fit an object in a container by giving its parent element to the position of relative so the properties of left, right, top and bottom only apply inside the container to move an object.

.container {
    position: relative;
}
.container .box {
    position: absolute;
    top: 0;
    left: 50%;
    right: 50%;
}
0
Subscribe to my newsletter

Read articles from USAMA USMAN directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

USAMA USMAN
USAMA USMAN