All about CSS Position Property!

All about CSS Position Property!

The position property specifies the type of positioning method used for an element. There are five different position values: • static • relative • fixed • absolute • sticky

image.png

Elements are then positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the position value.

Static Position

A static positioned element is always positioned according to the normal flow of the page. HTML elements are positioned static by default. Static positioned elements are not affected by the top, bottom, left, right, and z-index properties. In the example below, the green box "B" has a static position .
Syntax: .static { position: static; }

image.png

Relative Position

This acts similar to static positioning except that you can position it relative to itself using top, right, bottom, and left. Relative positioning tells the element to move relative to where it would have landed if it just had the default static positioning. If you give an element relative positioning and tell it to have a top of 40px, it moves down 40px from where it otherwise would have been.

Syntax: .relative { position: relative; top: 40px; left: 30px; }

The CSS above changes the position of Box-B as shown below.

image.png

Absolute Position

Absolute positioning tells the browser that the element being positioned should be removed from the normal flow of the document and will be placed in an exact location on the page based on the values specified on the top, bottom, left & right. it won't affect how the elements before it or after it in the HTML are positioned on the Web page. Absolute elements will by default head to the top-left of their closest parent that has a non-static position.

Syntax: .absolute { position: absolute; top: 10px; right: 0px; }

image.png

Fixed Position

Fixed elements are positioned relative to the entire HTML element. Fixed positioning is similar to absolute positioning, but, fixed positioning anchors an element to the browser window. If you scroll up and down, the fixed element stays put even as other elements scroll past.

Syntax: .fixed { position: fixed; top: 20px; right: 30px; }

image.png

Sticky Position

A sticky position is a combination of both Relative and Fixed positions into one. it starts as relative but once it scrolls out of the page it becomes a fixed position.

Syntax: .sticky { position: sticky; position: -webkit-sticky; top: 20px; right: 30px; }

Here is a codepen that includes the other positions including Sticky.

codepen.io/LindaOjo/pen/gOLeqaY