Css Positions

Css Positions

Hi My name is Tushar Kumar and I work as a Front-End Developer. My main motive behind this article is to help people learn about css positions as it is very important part of css and most asked interview question.. We'll explore all the various position types and learn about their implementation.

The position property allows us to define the position of an element. The Syntax : position: desiredPosition;

We have 5 Positions :

  1. Static
  2. Relative
  3. Absolute
  4. Fixed
  5. Sticky

Lets understand each and every position in detail with an example

positions.png

position: static;

  • Static : This is the default position of every HTML element.

static postion.png

position: relative;

  • It is used when we need to position an HTML element relative to its normal position(position where it is placed).
  • We can set the top, right, bottom, and left properties that will cause the element to adjust away from the normal position.
  • It leaves a gap as it shifted from its normal position

relative code.png

Output:

relative output.png

position: absolute;

  • An element with the absolute position will move according to the position of its parent element.
  • In the absence of any parent element, the HTML element will be placed relative to the page.
  • It doesnt leave a gap as it is relative to parent

absolute code.png

Output:

absolute output.png

position: fixed;

  • An element with position:fixed; will remain stuck to a specific position even after the page is scrolled.
  • This position property is used when we want to keep an HTML element at a fixed spot no matter where on the page the user is.
  • We can make chatbox using this property as it remains fixed even after scrolling
  • Notice the box fixed at the top right corner of the page in the image given below

fixed code.png

Output:

fixed output.png

position: sticky;

  • It is a hybrid of relative and fixed position.
  • An HTML element with position:sticky; will just sit there until a given position offset is met. -We can make a sticky navbar using this property

sticky code.png

Output: sticky output.png

Difference between Fixed and Sticky

  • If you make a particular element inside a container as fixed, then irrespective of container height, as we scroll, the element stays at the same position till you scroll to end of web page.

  • If you make an element as sticky and if its inside a container, then as you scroll, the element will be in the same position until the container height. While scrolling, if the container is also scrolled down, then the sticky element in the container will also move top with container.

Note - Please do practice after reading the artilcle and i hope the article helps you