CSS - Positionings
Soumil Bose
Immediate Joiner | Software Developement Engineer | Java | SpringBoot | Python | React | MERN
Many of us find it difficult to understand the css - positionings. Here I have explained the css posititionings with code and its output for easy understanding.
What is static, relative, absolute, and fixed ?
Static Positioning
It follows the default flow of the positions. When we add a new block element it positions automatically beneath the last block element.
Relative Positioning
This is relative to default position. As we explained in static positioning the default position of the green box is just beneath the red box.
Now we apply position = relative and we give external top and left property the box shifts by the mentioned pixel from its default position.
Absolute Posititioning
Position relative to nearest positioned ancestor or top left corner of web page
Suppose you have a <div> with no parent. So its default parent is <html> or the webpage itself. In that case when we mention position as absolute and provide top = 50px and left = 50px properties we have a <div> positioned 50px from top and left.
On the flip side suppose the <div color = "green"> has a parent <div color= "purple">.
Now two cases can arrive either the parent div has a mentioned position or it is default to static.
If the parent div's position = "static" then even if the child <div color = "green"> has position = "absolute" it still postitions itself to the webpage.
领英推荐
Case 1 : Parent div's position is relative. In this case the child div's parent is the purple div and it's position origin become top left corner of the purple div. Next when top and left property are applied it positions accordingly.
Case 2 : Parents div's position is absolute. In this case also the child <div color = "green">'s reference become its parent <div color = "purple"> and it positions itself accordingly.
Case 3 : Parents div's position is fixed. It is similar to absolute but the only difference is that the parent and child div sticks to that position. It doesnt scroll up or down from its position.
Fixed Positioning
This position is relative to the browser window.
If we mention a div's position as fixed then it is fixed at a relative top left position to the browser window. It doesnt move even if we scroll up or down.
As we can see the small yellow div is positioned as fixed 50px from top and 50px from left. It is stuck to that position.
Please like and drop a comment if you find this insightful. Follow if you want more concepts explained in simple and easy manner.
Senior Data Scientist
11 个月Interesting read