Positioning: Relative positioning

If you set position: relative on an element, you are now able to position it with an offset, using the properties

  • top
  • right
  • bottom
  • left

which are called offset properties. They accept a length value or a percentage.

Let’s create a parent container, a child container, and an inner box with some text:

<div class="parent">
  <div class="child">
    <div class="box">

with some CSS to give some colors and padding:

.parent {
  background-color: #af47ff;
  padding: 30px;
  width: 300px;

.child {
  background-color: #ff4797;
  padding: 30px;

.box {
  background-color: #f3ff47;
  padding: 30px;
  border: 2px solid #333;
  border-style: dotted;
  font-family: courier;
  text-align: center;
  font-size: 2rem;

here’s the result so far:

You can try and add any of the properties I mentioned before (top, right, bottom, left) to .box, and nothing will happen.

Because by default the positioning is set to static.

And those properties don’t do anything in this scenario.

Now if we set position: relative to .box, at first apparently nothing changes.

But now the element is now able to move using the top, right, bottom, left properties, and now you can alter the position of it relatively to the element containing it.

For example a negative value for top will make the box move up relatively to its container.

.box {
  position: relative;
  top: -60px;

Here’s this code in action:

Another example:

.box {
  position: relative;
  top: -60px;
  left: 180px;

Notice how the space that is occupied by the box remains unchanged in the container, like it was still in its place.

Another property that will now work is z-index to alter the z-axis placement. We’ll talk about it later on.

Lessons in this unit:

0: Introduction
1: ▶︎ Relative positioning
2: Absolute positioning
3: Fixed positioning
4: Sticky positioning
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!