17
Explore CSS positions
Before understanding anything, let’s know the default position of an element when it enters into a web page.
That’s the default look of these children with their parents (same here) which is static. HTML code for it looks like:
So, 1st child, 2nd child, 3rd child positions according to their HTML code. And this thing defines the “static” position.
Move forward to the “relative” position which is exactly the same as the “static” position. But we can move any element from 4 sides with the “relative” position.
We have changed the position of the 1st child with the “relative” position with 20px from the left. It means, the 1st child will occupy the position according to HTML code, but it will move itself 20px from the left. And, we get,
the 2nd, and 3rd child are in the same place/ position because none of the 4 attributes: top, left, right, bottom is used for them despite having position:relative. And for these 4 attributes, the element with the “relative” position moves itself over other elements and we have to set the same top/left/right/bottom attribute for getting the similar look like before which is so confusing.
Now, have a look at it:
Can you say why the 1st child has become an inline element??
No, it’s not behaving like an inline element. Actually other elements are ignoring it’s position and rendering themself as usual. Isn’t it drastical? No, it’s very useful sometimes. When you want to make anything fixed on a web page in any position, you can use it. And this is done relative to its parent container’s position. If no position is set to its parent, then it will occupy the top position of the viewport.
The code snippet:
So, you have to fix the position of the parent also.
With a fixed position, the element becomes fixed relative to the entire viewport. With scrolling, this element doesn’t leave its space and becomes visible over other elements. It differs from “absolute” in the sense that it is visible on screen with scrolling while “absolute” becomes invisible while scrolling.
The position “sticky” is the combination of “relative” & “fixed”. Without scrolling, the element with “sticky” behaves like “relative”. With scrolling, it becomes fixed. Fixed on which position on screen depends upon the 4 attributes: top/left/bottom/right.
Bingo!!! That's all for today.
17