...

/

The CSS Positioning Lesson You Never Had

The CSS Positioning Lesson You Never Had

After this lesson, you'll never have problems with positioning in CSS again. Period!

Introduction

Meet Janice and Roughnut.

Both are great buddies, and after grabbing coffee at a nearby coffee shop, the following conversation ensued.


Making Sense of the Story

I wasn’t intending to waste your time by reading a pointless story. Now, let me show you where this all comes to play.

In the real world, objects are typically placed with respect to some other object in a scene.

Take for example the cup in the story above.

Roughnut, like everyone else, went ahead and just placed the cup somewhere close to the table.

If only we were all a little more concious of this, we’d all notice that nothing is placed in empty space.

You’re always placing objects with respect to some other object in space.

Are you putting the cup on the table or the children to bed?

Did you see that?

Reference object + object to  be positioned
Reference object + object to be positioned

While positioning anything, there are always at least two objects involved.

  1. The object to be placed.
  2. The reference object.

Please refer to the graphic above.

Having established that, there’s one more thing to note.

After placing an object with respect to a reference object, you can accurately measure where they were placed.

For instance, when you place a cup on a table, you can measure exactly how many inches from the edges of the table the cup sits.

Don't have painful math memories. This is just an example
Don't have painful math memories. This is just an example

While nobody goes around monitoring the geometry of objects around them, this is important to the concept of positioning.

Let’s see how this applies to CSS.

Relative Positioning


.rel {
   position: relative;
}


What does the code above mean?

Let’s get back to the story.

When I say, ‘place the cup on the table’, I have made mention of two different objects.

  1. The object to be placed, the cup.
  2. The reference object, the table.

When you set the position property of an element to a value of relative, you’re setting it up as a reference object to position some other element.

Let’s get practical.

Consider the code output below:

The code above represents two divs placed side by side.

  1. The green div.
  2. The blue div.

In the blue div, there’s a child element represented by the small white box.

Consider yourself faced with the challenge of positioning the white box within the blue box.

Here’s my ...