Learn CSS Position in under 5 min
In this blog post, we are going to talk about CSS POSITION. CSS Positions help us design websites with ease. CSS allows us different methods for position elements. We'll see all the types of positions and learn about their use-cases.
This Position property allows us to define the position of an element and the syntax is : position: desiredposition;
We have five types of positions property for positioning an element:-
- position: static;
- position: relative;
- position: absolute;
- position: fixed;
- position: sticky;
Now we discuss all the five properties for positioning an element.
1. Static
This is the default position of every HTML element.
There’s not much that you can do with this position. The HTML element won't alter its position, no matter what values you associate with properties like
- top
- left
- right
- bottom
and also z-index property don't work.
2. Relative
In this position, the HTML element would shift relative to its original or initial position. To determine the amount of offset, set values for the top, right, bottom, and left properties. The other elements aren’t affected, but there will be extra space where the element would have been.
.Div { width: 100px; height: 100px; position: relative; top: 10px; left: 30px; }
3. Absolute
In position: absolute; the element ignores the normal document flow & is positioned with respect to its nearest positioned parent.
Its Basically the element is position relative to its nearsest parent position.
And if none of its parent is positioned, then the element is positioned according to the viewport or browser window and moves with scrolling.
4. Fixed
In position: fixed; the element is positioned relative to the viewport or window. as the name suggests, the HTML is fixed at the defined position, even if the page is scrolled. There's no space left where it would have been located in the page layout initially or originally.
Its totally fixed position even after you scroll or something. Its mainly use on web-page up-down navigation.
5. Sticky
In position: sticky; is combination of position relative and fixed. The element's position is determined by the user's scroll. The element will behave like a relative positioned element until the viewport meets a specified position. Then the element would get "fixed" in that spot.
The offset also does not work on the position of any other element.
So, that's the blogpost for CSS Positions.