Copied to clipboard

Mastering position absolute

Using position:absolute; allows us great flexibility with placing items on the page. Armed with the knowledge of how this works, you can effectively place anything anywhere on the screen.

This property is dependent on the size of the screen you're working on. This makes position:absolute; a good candidate for desktop-only projects.

About position:absolute

When you assign an element position:absolute; you are removing this element from the "flow" of the page. This means the element ignores all of the other stuff of the page and goes exactly where you tell it to go.

If you're going for exact placement of elements, I highly recommend working in a CodePen or another environment where you can see your code update automatically as you write it. This will be a huge help in tweaking things to be exact.

It can get a little unweildy to do things this way, because the entire webpage is essentially your canvas. Here is an example. I have placed a cat emoji at the top of this page, with the following styles:


This code tells the item to display 20 pixels from the top and 20 pixels from the left.

It's not bad, but if I wanted it in a very specific position, I'd have to take the entire page into account when calculating the pixel values. Things can get messy.

Instead of using the entire page as your "canvas", you can designate another element - like a div - as the canvas for your absolutely positioned items.

In the example below, both the heart and the globe images are positioned absolutely at top:10px; and right:10px;. The difference is that the heart image is inside of a container with position:relative;

See the Pen Position Anything Anywhere - 1.5 (Container) by Sadness (@sadness97) on CodePen.

Once you are working inside of a relative element, the top, left, bottom and right values will be relative to that container.

In the below example, I assigned classes to each image so I can use those to style them. If you're just using this technique on one page, it may save you time to add the styles inline.

Once you have all of your images on the page, you can start to assign each one position values (top, left, right and bottom). In my experience it's usually easiest to keep things consistent by sticking to either top and left and right and bottom positioning. Mixing them all together might make things confusing.

Here is an example of custom positioning of the images:

See the Pen Position Anything Anywhere - 3 (Position Items) by Sadness (@sadness97) on CodePen.

Defying boundaries

Even if you use a relatively positioned container, you can still bring your items outside of the container - with negative margins.

This can create some very cool effects.

See the Pen Position Anything Anywhere - 4 (Defy Boundaries!!) by Sadness (@sadness97) on CodePen.