fbpx
You have 4 free member-only stories remaining for the month. Subscribe now for unlimited access

CSS Positioning – Explained!

Last night, I spent my time turning my blog’s theme to dark mode. After lots of CSS tweaks, Google searches, Reddit questions, and learning few tags, it finally came to life.

You can check out the blog here

Well, this led me to learn, more like, revise CSS positioning, and I thought, well, why not make it easy for others too. Here we go!

Positioning

Ask yourself, what you think of ‘positioning’ something. You’re basically telling it where to reside, right? Now, a webpage is made up of combination of boxes.

Positioning in CSS means, to set the position of an element in the webpage.

P.S: This is the code I used to show these blocks

* {
outline: 2px solid #1a1a1a;
}

Ever noticed how the top nav bar stays at top even when you scroll the screen. Yep, that’s because it is positioned to act that way.

Let’s see the first one, shall we?

position: static;

This is the default position for all HTML elements. It is positioned with the normal flow of the webpage just like these texts. You can’t use top, bottom, left, right properties with this.

div. static {
position: static;
border: 3px solid #73AD21;
}

That was easy, right? It makes element static with respect to the webpage.

position: relative;

Now, what if you want to specify directions to a particular element while being static, well, this is where relative position comes into play.

div. static {
position: relative;
left: 30px;
border: 3px solid #73AD21;
}

Note: Other content will not be adjusted to fit into any gap left by the element.

In a nutshell, relative without any direction property acts like static.

position: fixed;

The name gives it away, doesn’t it? The element stays fixed at the specified place on the viewport, no matter what!

The browser’s viewport is the area of the window in which web content can be seen. This is often not the same size as the rendered page, in which case the browser provides scrollbars for the user to scroll around and access all the content.
– MDN

Viewport is basically that area of the content you see on the screen, it varies across devices.