CSS - Positionings

CSS - Positionings

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.

Static Position

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.

Relative Positioning

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.

Absolute position with no parent

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.

Absolute position with parent as static

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.

Absolute position with parent as relative

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.

Absolute position with parent as absolute

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.

Absolute position with parent as fixed

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.





Sayantan Sinha

Senior Data Scientist

11 个月

Interesting read

要查看或添加评论,请登录

社区洞察

其他会员也浏览了